C# - 遍历DataRepeater中所有行的最佳方法是什么?

3
private void exam_Load(object sender, EventArgs e)
    {
        GetCount();

        MySqlConnection con = new MySqlConnection("server = localhost; user id = root; password =; database = dbtest1;");
        MySqlCommand cmd = new MySqlCommand("SELECT question, question_no, choice1, choice2, choice3, choice4 from quiz_tions where quiz_id = '" + lid + "' ORDER BY RAND() LIMIT " + count + ";", con);
        MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        label5.DataBindings.Add("Text", dt, "question");
        label6.DataBindings.Add("Text", dt, "question_no");
        rb1.DataBindings.Add("Text", dt, "choice1");
        rb2.DataBindings.Add("Text", dt, "choice2");
        rb3.DataBindings.Add("Text", dt, "choice3");
        rb4.DataBindings.Add("Text", dt, "choice4");
        dataRepeater1.DataSource = dt;

        LoadData();


        label1.Text = qtitle;
        label3.Text = qtype;
    }

我在表单上使用了一个 DataRepeater 控件,并使用上面的代码进行填充。每次执行这段代码时...

private void button3_Click(object sender, EventArgs e)
    {
        foreach (DataRepeaterItem c in dataRepeater1.Controls)
        {
            ss += ((Label)c.Controls["label5"]).Text + "\n";
        }
        MessageBox.Show(ss);
        ss = "";
    }

在单击按钮之前单击不同行时,结果会有所不同(有时为3行,有时为4行),因为在执行此操作时我的DataRepeater控件上有5行。这是为什么?遍历DataRepeater的行的正确方法是什么?
另一个问题(也许与我的帖子无关)是每当我在DataRepeater上向下/向上滚动时,它有时会自动勾选列表中的随机RadioButton。这个控件有什么问题?

仍然是一样的 :( - ItaChi
你确定在某些重复项中 label5.Text 不是空的吗? - M. Wiśnicki
是的,它们不是空的。 - ItaChi
ss is a TextBox type? If yes try ...+ "\r\n" instead ...+"\n" - M. Wiśnicki
foreach (DataRepeaterItem c in dataRepeater1.Controls) { ss += ((Label)c.Controls["label5"]).Text + "\n"; }MessageBox.Show(ss); 这段代码应该在一个 MessageBox 中返回 5 行文本,但实际上它并没有。 - ItaChi
显示剩余2条评论
1个回答

1
如果您使用多行文本框TextBox,应该使用\r\n而不是\n

Windows文本框需要CRLF作为行终止符,而不仅仅是LF。

您可以使用\r\n

 ss += ((Label)c.Controls["label5"]).Text + "\r\n";

或者 System.Environment.NewLine
ss += ((Label)c.Controls["label5"]).Text  + System.Environment.NewLine;

或者 StringBuilder。
 var sb = new StringBuiler();
 foreach (DataRepeaterItem c in dataRepeater1.Controls)
 {
    sb.AppendLine(((Label)c.Controls["label5"]).Text);
 }

 ss+= sb;

使用 trim 函数来删除任何额外的字符。((Label)c.Controls["label5"]).Text.Trim(); - Mukul Varshney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接