.NET 3.5 Listbox Selected Values (Winforms)

你说的曾经没有我的故事 提交于 2019-11-29 08:45:33

Try casting each object in the collection to the desired type. For example, if my items are of type Customer, I could do something like this...

var selected = listBox1.SelectedItems;

foreach ( var item in selected )
{
    var singleCustomer = (Customer)item;
}

Now you can get any property you want from the Customer.

This is just a trivial example, but I'm sure you can apply the concept to your problem.

UPDATE (after question was updated to indicate the Listbox is bound to table):

If you're bound to a DataTable, you could try something like this (again, trivial but relevent):

var selected = listBox1.SelectedItems;

foreach ( var item in selected )
{
    var itemArray = ( (DataRowView)item ).Row.ItemArray;

    var name = itemArray[0];
    var id = itemArray[1];
}

SelectedItems is what you want.

SelectedItem and SelectedValue are only different when you set DisplayMember and ValueMember. I don't think this is supported for Multi-select.

What type of Items are you adding to the listbox?

Element [0] will be the "ValueMember", and element [1] will be the "DisplayMember". Assuming the OP's "ID" field is an integer, try the following:

int selectedCount = lstBxOb10Customer.SelectedItems.Count;
int[] selectedIDs = new int[selectedCount];
string[] selectedNames = new string[selectedCount];

for (int selected = 0; selected < selectedCount; selected++)
{
    var itemArray = ( (DataRowView)item ).Row.ItemArray;

    selectedIDs[selected]  = (int)itemArray[0];
    selectedNames[selected]  = (string)itemArray[1];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!