如何将选中复选框中的信息后的逗号放入文本框?

时间:2012-06-29 06:02:44

标签: c# asp.net

       foreach (GridViewRow row in GridView1.Rows)         
       {           
        var chk = row.FindControl("myCheckBox") as CheckBox;
        if (chk.Checked)
        {
        var email = row.FindControl("LabelEmail") as Label;
        txtEmails.Text += (string.Join(",", email.Text));
        }

我正在从网格视图中提取电子邮件,并假设将电子邮件相应地用逗号分隔它们。我尝试使用string.join方法,但它根本没有出现在文本框中。我尝试不使用string.join,但每封电子邮件旁边都会添加逗号。如何正确分离电子邮件?

示例:Helloworld @ gmail.com,Helloeveryone @ gmail.com,HelloBye @ gmail.com

2 个答案:

答案 0 :(得分:2)

而不是:

txtEmails.Text += (string.Join(",", email.Text));

试试这个:

txtEmails.Text += email.Text + ", ";

编辑:

因为它在上一封电子邮件中添加了逗号,您可以执行以下操作来阻止:

int counter = 0;
// The counter variable must be global
foreach (GridViewRow row in GridView1.Rows)         
{           
    var chk = row.FindControl("myCheckBox") as CheckBox;
    if (chk.Checked)
    {
        counter++;
        var email = row.FindControl("LabelEmail") as Label;
        if (counter <= 1)
        txtEmails.Text += email.Text;
        else
        txtEmails.Text += ", " + email.Text;
    }
}

希望这有帮助!

答案 1 :(得分:2)

string.Join使用字符串数组,如果你传递一个简单的字符串,就像你的情况一样,你不会看到任何变化。我想你想在每个电子邮件地址之后追加,如果你为你的情况使用StringBuilder那就更好了

StringBuilder sb = new StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
        {
            var chk = row.FindControl("myCheckBox") as CheckBox;
            if (chk.Checked)
            {
            var email = row.FindControl("LabelEmail") as Label;
            sb.Append(email.Text);
            sb.Append(",");
            }

最后你可以这样做:

string strEmails = sb.ToString().TrimEnd(','); // TrimEnd to remove the last comma

稍后您可以指定

textEmails.Text = strEmails;