2013-02-19 86 views
0

我有一个简单的带有文本框,按钮和标签控件的ASP.net程序。使用带分隔符的+ =运算符

在按钮单击事件上,我将文本框文本分配给标签文本并每次使用赋值运算符添加到它。我使用逗号分隔值。

protected void Button1_Click(object sender, EventArgs e) 
{ 
    Label1.Text += TextBox1.Text + ","; 
} 

问题是这段代码给了我一个额外的逗号。例如如果值1,2,3,4和5在文本框中输入,标签文本将是:

1,2,3,4,5, 

我需要它是:

1,2,3,4,5 

有人能帮忙吗?

+1

你为什么不直接删除最后一个逗号,为例如通过采取一个子字符串0 ... length - 2. – 2013-02-19 22:15:34

+0

现在我很好奇,为什么在按钮单击时在TextBox1.Text的末尾添加一个逗号,如果您已经在文本框中输入逗号。 – 2013-02-19 22:47:04

回答

4

调整完毕后,这样做:

Label1.Text.Trim(','); 
+0

你能解释一下你说的“完成”是什么意思吗? – Steve 2013-02-19 22:25:20

+0

这意味着,在你保存或做任何你要处理的Label.Text当前具有值1,2,3,4,5时,只需使用Label1.Text.Trim(',')修剪掉逗号; – 2013-02-19 22:29:00

+0

那么,trim()第一次只剩下1,第二次点击会发生什么?你会得到一个“12”而不是1,2。 OP说“每一次”意味着他希望点击多次 – Steve 2013-02-19 22:31:58

3

第一次只是分配textbox.text,再加入第一个逗号那么textbox.text

protected void Button1_Click(object sender, EventArgs e) 
{ 
    if(Label1.Text.Length == 0) 
     Label1.Text = TextBox1.Text; 
    else 
     Label1.Text += "," + TextBox1.Text; 
} 
2
protected void Button1_Click(object sender, EventArgs e) 
{ 
    if(Label1.Text.Lenght <= 0) 
     Label1.Text = TextBox1.Text; 
    else 
     Label1.Text += "," + TextBox1.Text; 
} 
1

尝试:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    Label1.Text += (Label1.Text.Length == 0 ? "" : ",") + TextBox1.Text; 
} 

This这样你在前面加上一个逗号所添加的文本只在标号为空

2

首先附加逗号,除非该标签是空白

protected void Button1_Click(object sender, EventArgs e) 
{ 
    if (String.IsNullOrEmpty(Label1.Text)) 
     Label1.Text = TextBox1.Text; 
    else 
     Label1.Text += "," + TextBox1.Text; 
} 
1
Label1.Text += string.IsNullOrEmpty(Label1.Text) ? TextBox1.Text : string.Format(",{0}", TextBox1.Text);