且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将多个项目从列表框添加到文本框

更新时间:2023-10-14 12:26:58

除了其他响应者所说的之外,我将使用StringBuilder来组合字符串.将大量字符串组合在一起时,通常***使用StringBuilder.另外,我将使用object.ReferenceEquals来比较两个对象,而不是使用默认的inequality运算符.

另外,我知道您不要求在每个逗号后插入换行符,因此您可以将其从响应者提供给您的代码中删除.但是,如果您确实想插入换行符,则可以使用Environment.NewLine而不是"\ r \ n".

创建StringBuilder后,调用ToString并将结果分配给您正在使用的TextBox的Text属性.
In addition to what the other responder said, I''d use a StringBuilder to combine the strings. It''s generally a good idea to use a StringBuilder when combining a significant number of strings together. Also, instead of using the default inequality operator, I''d use object.ReferenceEquals to compare the two objects.

Also, I know you didn''t ask for a newline to be inserted after each comma, so you can take that out of the code the responder gave you. But if you do want to insert a newline, I''d use Environment.NewLine rather than "\r\n".

Once you are done creating the StringBuilder, call ToString and assign the result to the Text property of the TextBox you are using.


如果您知道如何处理列表框中的多行,只需将这些值一起添加到字符串中,然后将字符串的值分配给文本框,或直接分配给文本框.
If you know how to process multiple lines out of a list box, simply append the values together either into a string, then assign the value of the string to the text box, or directly into the text box.


好吧,我的解决方案是:

考虑我们在窗体上有一个列表框,其"SelectionMode"属性设置为值"MultiSimple",以及一个文本框,其"Multiline"属性为true,而"WordWrap"属性为false.当然还有一个按钮,用于将列表框中的项目添加到文本框中.

我在"button1_Click"事件中的代码为:

private void button1_Click(对象发送者,EventArgs e)
{
int count = listBox1.SelectedItems.Count;

foreach(listBox1.SelectedItems中的对象项)
{
textBox1.Text + = item.ToString();

如果(listBox1.SelectedItems [count-1]!= item)
textBox1.Text + =,\ r \ n";
}
}

因此,列表框中的每个选定项都将添加(通过ToString()函数作为字符串)到文本框的文本中,如果不是最后一个选定项,则将添加逗号和新行.

------------------------
问候

H.Maadani
Well, my solution for that would be :

consider we have a listbox on form, with its ''SelectionMode'' property set to value ''MultiSimple'', and a textbox which ''Multiline'' property is true, and ''WordWrap'' property is false. and of course a button to add items from listbox to textbox.

my code in the ''button1_Click'' event would be :

private void button1_Click(object sender, EventArgs e)
{
int count = listBox1.SelectedItems.Count;

foreach (object item in listBox1.SelectedItems)
{
textBox1.Text += item.ToString();

if (listBox1.SelectedItems[count - 1] != item)
textBox1.Text += ", \r\n";
}
}

So, each selected item in listbox will be added ( as an string via ToString() function) to textbox''s text, and if it isnt the last selected item, a comma and a new line will be added.

------------------------
Regards

H.Maadani