.NET 3.5 Listbox Selected Values (Winforms)

后端 未结 3 1336
时光说笑
时光说笑 2020-12-18 14:11

I am BATTLING to get the selected values (please note VALUES not TEXT) from a Winforms Listbox that has multi-select enabled and has been bound to a database table getting t

3条回答
  •  醉话见心
    2020-12-18 14:41

    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];
    }
    

提交回复
热议问题