问题描述
|
我目前有一个字符串发送到TextBox,但是可以将其发送到列表框吗?
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();
}
解决方法
您可以将加入的任务名称添加为单个项目
listbox1.Items.Add(string.Join(Environment.NewLine,taskNames));
或者您可以将每个任务名称添加为单独的项目
foreach (var taskName in taskNames)
{
listbox1.Items.Add(taskName);
}
, 无需设置文本框的Text
属性,而是将ListItem
添加到列表框的Items集合中。
lstBox.Items.Add(new ListItem(string.Join(Environment.NewLine,taskNames));
要么...
foreach(var taskName in taskNames)
lstBox.Items.Add(new ListItem(taskName));
, 对于WinForms:
listView.Items.Add(string.Join(Environment.NewLine,taskNames));
, ListBox具有Items属性。您可以使用Add()方法将对象添加到列表中。
listBox.Items.Add(\"My new list item\");
, 使用AddRange,这可以接收一个对象数组。
这是一些示例代码:
启动一个新的WinForms项目,将一个列表框放到窗体上:
string[] names = new string[3];
names[0] = \"Item 1\";
names[1] = \"Item 2\";
names[2] = \"Item 3\";
this.listBox1.Items.AddRange(names);
对于您的特定示例:
// Get an array of all the task names
string[] taskNames = st.GetTaskNames();
this.listBox1.Items.AddRange(taskNames);
如果重复调用此命令,请在添加项目之前根据需要调用clear:
this.listBox1.Items.Clear();
, 几秒钟的谷歌搜索价值
foreach(String s in taskNames) {
listBox1.Items.add(s);
}