How to Find ListBox1.SelectedItem in other ListBox2 Items
I want to filtering Items of one list and show result into another list. when i fill first ListBox by calling .Items.Add()
it works fine. but when i fill it by a table by .DataSource
property of it, it works fine too but i can not save .selectedItem
of first list and select it in second listbox.
I have ListBox1 in my form and fill it by a table returned from database on Form_Load
event.
i also have a button that write on Button_Click
event:
//saving selected item by user in the first 开发者_如何学CList
object selectedItem = listBox1.SelectedItem;
// filtering rows in the first List and showing into second List
DataTable dtable = (DataTable)listBox1.DataSource;
var x = (from drow in dtable.AsEnumerable()
where drow["name"].ToString().ToUpper().StartsWith(textBox1.Text.ToUpper())
select drow).AsEnumerable();
listBox2.DataSource = null;
if (x.Count() > 0)
listBox2.DataSource = x.CopyToDataTable();
listBox2.DisplayMember = listBox1.DisplayMember;
listBox2.ValueMember = listBox1.ValueMember;
//setting the selected item in the second list
if (selectedItem != null && listBox2.Items.Contains(selectedItem))
listBox2.SelectedItem = selectedItem;
but in result, ListBox2 wont select selected item in ListBox1 because last if
would not be true.
please tell me what is wrong. thanks
I found solution:
//setting the selected item in the second list
if (selectedItem != null)
listBox2.SelectedItem = (
from item in listBox2.Items.Cast<DataRowView>()
where item[listBox2.ValueMember].ToString() == ((DataRowView)selectedItem)[listBox1.ValueMember].ToString()
select item).FirstOrDefault();
Your problem is the use of method CopyToDataTable. If you read it's summary:
Returns a System.Data.DataTable that contains copies of the System.Data.DataRow objects, given an input System.Collections.Generic.IEnumerable object where the generic parameter T is System.Data.DataRow.
This implies that at the time of your 'if' comparison listBox2.Items contains different instances (with same information) than contained in listbox1.DataSource - this includes listbox1.SelectedItem and therefore listbox2.Items never contains listbox1.SelectedItem.
The selectedItem object of listBox1 will not be in listBox2. This is due to the line listBox2.DataSource = x.CopyToDataTable() which creates a new list. The two listbox are pointing to the same datasource but they are represented in each listbox with completely different ListItems.
A solution to this is to just iterate the listBox2 and search for the selected item.
精彩评论