C#将listbox的项多选并赋值给另一个listbox
时间: 2024-12-19 07:14:08 浏览: 70
在C#中,Listbox控件默认是以单选或多选模式工作的,如果你想让ListBox支持多选,并将选中的项目复制到另一个ListBox,可以按照以下步骤操作:
1. **设置ListBox的SelectionMode**:
首先,确保你的第一个ListBox(源ListBox)的SelectionMode属性设置为`MultiSelect`,以便用户可以选择多个项目。
```csharp
sourceListBox.SelectionMode = SelectionMode.MultiSimple;
```
2. **获取选中的项目**:
使用`SelectedItems`属性来获取已选择的所有项目,这个属性返回的是一个Object数组,因为ListBox可以包含不同类型的数据。
```csharp
object[] selectedItems = sourceListBox.SelectedItems;
```
3. **遍历和复制项目**:
创建一个新的列表,然后将每个选中的项目转换为你想要的目标类型,并添加到新列表中。这里假设你有一个`MyItem`类,你可以这样做:
```csharp
List<MyItem> targetList = new List<MyItem>();
foreach (object selectedItem in selectedItems)
{
if (selectedItem is MyItem item) // 检查是否是MyItem类型的实例
{
targetList.Add((MyItem)item);
}
}
```
4. **填充目标ListBox**:
将复制后的项目添加到目标ListBox:
```csharp
targetListBox.Items.AddRange(targetList.ToArray());
```
5. **更新视图**:
最后,如果你需要,可以刷新两个ListBox的显示:
```csharp
sourceListBox.SelectedIndex = -1; // 清除源ListBox的选择
targetListBox_SelectedIndexChanged(null, EventArgs.Empty); // 可能需要手动触发目标ListBox的选中事件处理方法
```
阅读全文
相关推荐


















