Get SelectedItems from database fed ListBox

▼魔方 西西 提交于 2020-01-04 13:11:55

问题


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.


回答1:


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();



回答2:


string[] items = listBoxAtribute.SelectedItems.Select(x => x.Item[0]);    



回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/11117932/get-selecteditems-from-database-fed-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!