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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:08:20  来源:igfitidea点击:

Sending a string to a listbox (C#)

c#.netwindowswinformslistbox

提问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 Textproperty, add a ListItemto 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.

ListBox has Itemsproperty. You can use Add()method to add object to list.

ListBox 具有Items属性。您可以使用Add()方法将对象添加到列表中。

listBox.Items.Add("My new list item");

回答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();

回答by iAndr0idOs

A couple seconds worth of googling

几秒钟的谷歌搜索

foreach(String s in taskNames) {
    listBox1.Items.add(s);
}