c#listbox多项输出
时间: 2023-11-24 21:47:36 浏览: 33
要在 C# 中输出 ListBox 中的多项,可以使用以下代码:
```
foreach (var item in listBox1.SelectedItems)
{
Console.WriteLine(item.ToString());
}
```
其中,`listBox1` 是 ListBox 控件的名称,`SelectedItems` 属性返回一个集合,包含了 ListBox 中被选中的项。上述代码使用 `foreach` 循环遍历这个集合,并输出每个被选中项的字符串表示。
相关问题
c#listbox控件多线程
在C#中,如果要在一个ListBox控件中显示多个线程的信息,可以使用Invoke方法将更新ListBox控件的操作委托到UI线程中。
例如,下面的示例代码演示了如何使用ListBox控件显示多个线程的信息:
```csharp
private void btnStart_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(new ThreadStart(ThreadMethod1));
Thread thread2 = new Thread(new ThreadStart(ThreadMethod2));
thread1.Start();
thread2.Start();
}
private void ThreadMethod1()
{
for (int i = 0; i < 10; i++)
{
UpdateListBox("Thread 1: " + i.ToString());
Thread.Sleep(1000);
}
}
private void ThreadMethod2()
{
for (int i = 0; i < 10; i++)
{
UpdateListBox("Thread 2: " + i.ToString());
Thread.Sleep(1500);
}
}
private void UpdateListBox(string message)
{
if (listBox1.InvokeRequired)
{
listBox1.Invoke(new Action<string>(UpdateListBox), message);
}
else
{
listBox1.Items.Add(message);
}
}
```
在这个例子中,当用户单击Start按钮时,程序会创建两个线程ThreadMethod1和ThreadMethod2,并在每个线程中循环10次,每隔1秒或1.5秒将一条消息添加到ListBox控件中。 UpdateListBox方法用于更新ListBox控件,如果需要更新操作,则通过Invoke方法将操作委托到UI线程中。
C# listbox
回答: 在C#中,listbox是一种用于显示和选择列表项的控件。可以使用listbox的属性和方法来添加、删除和清空列表项。引用\[1\]中的代码演示了如何获取listbox中选中项的内容并显示在textbox中。引用\[2\]中的代码演示了如何在listbox中添加和删除选中项。使用listbox的Items属性可以访问列表项集合,可以使用Add方法将新的项添加到列表的末尾,使用Insert方法在指定位置插入新的项,使用Remove方法删除指定的项,使用Clear方法清空列表中的所有项。此外,可以使用ClearSelected方法取消所有选中项。
#### 引用[.reference_title]
- *1* *3* [c#listbox使用详解和常见问题解决](https://blog.csdn.net/weixin_30615767/article/details/94860218)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [C#开发之——ListBox(12.13)](https://blog.csdn.net/Calvin_zhou/article/details/107670890)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]