我想筛选一个列表的项目并将结果显示到另一个列表中。当我填写第一个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
不会是真实的。
请告诉我什么是错的。谢谢
如果声明之前,尝试调用listBox2的DateBind方法。 – Adeel
@Adeel ListBox2没有这个方法。我的申请是windows base – ahoo
@ahoo,对不起,我无法理解你的英文,你是说当你选择列表框1中的一些项目时,你希望列表框2中的相同项目被选中可用? –