2011-08-22 37 views
1

我想筛选一个列表的项目并将结果显示到另一个列表中。当我填写第一个ListBox通过调用.Items.Add()它工作正常。但是当我通过.DataSource属性填充它的表时,它也可以正常工作,但我无法保存第一个列表的.selectedItem并在第二个列表框中选择它。如何在其他ListBox2项目中查找ListBox1.SelectedItem

我在我的表单中有ListBox1,并通过在事件中从数据库返回的表填充它。

我也有上Button_Click事件写一个按钮:

  //saving selected item by user in the first List 
     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; 

但结果,ListBox2不会选择在ListBox1中选择的项目,因为最后if不会是真​​实的。

请告诉我什么是错的。谢谢

+0

如果声明之前,尝试调用listBox2的DateBind方法。 – Adeel

+1

@Adeel ListBox2没有这个方法。我的申请是windows base – ahoo

+0

@ahoo,对不起,我无法理解你的英文,你是说当你选择列表框1中的一些项目时,你希望列表框2中的相同项目被选中可用? –

回答

1

我找到了解决办法:

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

你的问题是使用方法CopyToDataTable。如果你读它的摘要:

返回包含的System.Data.DataRow对象的拷贝一个System.Data.DataTable,给定的输入System.Collections.Generic.IEnumerable对象,其中泛型参数T系统。 Data.DataRow。

这意味着在你的“如果”比较listBox2.Items的时间包含比包含在listbox1.DataSource不同的情况下(有相同的信息) - 这包括listbox1.SelectedItem因此listbox2.Items决不会包含ListBox1中。的SelectedItem。

0

listBox1的selectedItem对象将不在listBox2中。这是由于行listBox2.DataSource = x.CopyToDataTable(),它创建一个新的列表。这两个列表框指向相同的数据源,但它们在每个列表框中用完全不同的ListItems表示。

解决方案是迭代listBox2并搜索所选项目。

相关问题