如何将文本项添加到已与数据源绑定的winform列表框中
本文关键字:绑定 数据源 winform 列表 文本 添加 | 更新日期: 2023-09-27 18:19:06
我有一个已经绑定到data source
的c# Winform
Listbox
。
var custList=Cusomer.CustomerList();
lstbox.DataSource=custList;
`enter code here`
lstbox.DisplayMember="CustName";
lstbox.ValueMemebr="CustId";
现在我想添加一个名为"All"的文本到相同的list box
,以便它应该显示为第一个listitem
。此外,通过binding
添加的列表项也应该出现在那里。我的想法是,当用户选择"ALL"选项时,所有的列表项都必须自动选择。
任何想法我可以添加新的文本值?
谢谢。
使用ListBox.Items.Insert
并指定0
作为索引。
ListBox1.Items.Insert(0, "All");
希望这对你有帮助。
void InitLstBox()
{
//Use a generic list instead of "var"
List<Customer> custList = new List<Customer>(Cusomer.CustomerList());
lstbox.DisplayMember = "CustName";
lstbox.ValueMember = "CustId";
//Create manually a new customer
Customer customer= new Customer();
customer.CustId= -1;
customer.CustName= "ALL";
//Insert the customer into the list
custList.Insert(0, contact);
//Bound the listbox to the list
lstbox.DataSource = custList;
//Change the listbox's SelectionMode to allow multi-selection
lstbox.SelectionMode = SelectionMode.MultiExtended;
//Initially, clear slection
lstbox.ClearSelected();
}
如果你想在用户选择all时选择所有客户,添加这个方法:
private void lstbox_SelectedIndexChanged(object sender, EventArgs e)
{
//If ALL is selected then select all other items
if (lstbox.SelectedIndices.Contains(0))
{
lstbox.ClearSelected();
for (int i = lstbox.Items.Count-1 ; i > 0 ; i--)
lstbox.SetSelected(i,true);
}
}
当然,不要忘记设置事件处理程序:)
this.lstbox.SelectedIndexChanged += new System.EventHandler(this.lstbox_SelectedIndexChanged);