我有一个问题,因为一段时间现在只是无法找到适合我的解决方案。我有ListBox
,其中填充了DataTable
之类的
listbox.DataSource = table;
listbox.Displaymember = "Name";
listbox.ValueMember = "ID";
如果我现在在列表框中选择一个项目,我可以像:
listbox.SelectedValue.toString();
我的问题:
如果我希望从启用了多项选择的ListBox
中选择所有选定的值,并将它们全部保存在数组或类似内容中,我该怎么办?!
我无法使用SelectedItems
因为没有向我提供我需要的信息。
答案 0 :(得分:3)
或者,如果您只想迭代所选项目,可以使用SelectedIndices
属性:
foreach (int i in listbox.SelectedIndices)
{
// listbox.Items[i].ToString() ...
}
或者:
foreach (var item in listbox.SelectedItems)
{
MessageBox.Show(item.ToString());
}
答案 1 :(得分:3)
试试这个:
var lst = listBox1.SelectedItems.Cast<DataRowView>();
foreach (var item in lst)
{
MessageBox.Show(item.Row[0].ToString());// Or Row[1]...
}