ListBox multiple Selection获取所有选中的值



我有一个问题,因为现在只是找不到任何解决方案,为我工作。我有一个ListBox填充了一个DataTable,比如

listbox.DataSource = table;  
listbox.Displaymember = "Name";    
listbox.ValueMember = "ID";

如果我现在选择列表框中的一个项目,我可以把它取出来,像这样:

listbox.SelectedValue.toString();
我问题:

我能做什么,如果我想从一个ListBox的所有选择值,其中多个选择被启用,并将它们全部保存在一个数组或类似的东西?

我不能使用SelectedItems,因为它不能提供我需要的信息。

或者如果你只想迭代选中的项目,你可以使用SelectedIndices property:

foreach (int i in listbox.SelectedIndices)
{
    // listbox.Items[i].ToString() ...
}

或:

foreach (var item in listbox.SelectedItems)
{
    MessageBox.Show(item.ToString());
}

试试这个:

var lst = listBox1.SelectedItems.Cast<DataRowView>();
foreach (var item in lst)
{
     MessageBox.Show(item.Row[0].ToString());// Or Row[1]...
}

最新更新