windows 将字符串发送到列表框 (C#)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6431088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending a string to a listbox (C#)
提问by Mathew
I currently have a string being sent to a TextBox, although instead is it possible to send it to a listbox?
我目前有一个字符串被发送到文本框,但是否可以将它发送到列表框?
private void buttonLB_Click(object sender, EventArgs e)
{
string machineName = (@"\" + System.Environment.MachineName);
ScheduledTasks st = new ScheduledTasks(machineName);
// Get an array of all the task names
string[] taskNames = st.GetTaskNames();
richTextBox6.Text = string.Join(Environment.NewLine, taskNames);
st.Dispose();
}
回答by David Ruttka
You can add the joined task names as a single item
您可以将加入的任务名称添加为单个项目
listbox1.Items.Add(string.Join(Environment.NewLine, taskNames));
Or you can add each of the task names as a separate item
或者您可以将每个任务名称添加为单独的项目
foreach (var taskName in taskNames)
{
listbox1.Items.Add(taskName);
}
回答by FishBasketGordo
Instead of setting the textbox's Text
property, add a ListItem
to the listbox's Items collection.
不要设置文本框的Text
属性,而是将 a 添加ListItem
到列表框的 Items 集合。
lstBox.Items.Add(new ListItem(string.Join(Environment.NewLine, taskNames));
Or...
或者...
foreach(var taskName in taskNames)
lstBox.Items.Add(new ListItem(taskName));
回答by yas4891
For WinForms:
对于 WinForms:
listView.Items.Add(string.Join(Environment.NewLine, taskNames));
回答by Renatas M.
回答by Jon Raynor
Use AddRange, this can take an array of objects.
使用 AddRange,这可以接受一个对象数组。
Here's some sample code:
这是一些示例代码:
Start a new WinForms project, drop a listbox on to a form:
启动一个新的 WinForms 项目,将列表框拖放到表单上:
string[] names = new string[3];
names[0] = "Item 1";
names[1] = "Item 2";
names[2] = "Item 3";
this.listBox1.Items.AddRange(names);
For your specific example:
对于您的具体示例:
// Get an array of all the task names
string[] taskNames = st.GetTaskNames();
this.listBox1.Items.AddRange(taskNames);
If this is called repeatedly, call clear as needed before adding the items:
如果重复调用,请在添加项目之前根据需要调用 clear:
this.listBox1.Items.Clear();