简体   繁体   中英

Get SelectedItems from database fed ListBox

I need to get values from selected items from listbox which is binding from database. But if I try

listBoxAtribute.SelectedItems[0].ToString()

it returns System.Data.DataRowView

Is there any way to convert Data from DataRowView to string ?

My idea looks like this:

for(int i = 0; i < listBoxAtribute.SelectedItems.Count; i++)
{
  MessageBox.Show(listBoxAtribute.SelectedItems[i].Tostring);
}

Thanks a lot for any reply.

Try casting selected item of listbox to DataRowItem first and access columns value passing column name to indexer

Here is the sample

((DataRowView)Listbox.SelectedItem)["<column_name>"].ToString();

If you want to show fist column value, then take fist item of listBoxAtribute.SelectedItem as

for(int i = 0; i < listBoxAtribute.SelectedItems.Count; i++)
{
  MessageBox.Show(listBoxAtribute.SelectedItems[i].Item[0]); 
}
string[] items = listBoxAtribute.SelectedItems.Select(x => x.Item[0]);    

Under the assumption that you are seeing, visibly that is, a single specific column from said database driven entries, that would indicate that you have the DisplayMember property of the listbox set. Possibly the ValueMember as well, assuming you are using EditValue anywhere. I would write something along these lines.

((DataRowView)listBoxAtribute.SelectedItems[0])[listBoxAtribute.DisplayMember].ToString();

That way you get exactly what the user would see on the screen. Now, if you want a different piece of data than the one shown on the screen, you would need to use user968441's approach and hard code the column name. But that's also relatively easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM