C# 如何将文本项添加到已与数据源绑定的winform列表框中
我有一个c#C# 如何将文本项添加到已与数据源绑定的winform列表框中,c#,.net,listbox,bind,listitem,C#,.net,Listbox,Bind,Listitem,我有一个c#Winform列表框,它已经绑定到一个数据源 var custList=Cusomer.CustomerList(); lstbox.DataSource=custList; `enter code here` lstbox.DisplayMember="CustName"; lstbox.ValueMemebr="CustId"; 现在,我想在同一个列表框中添加一个名为“All”的文本,以便将其显示为第一个列表项。此外,通过绑定添加的列表项也应存在于此处。我的想法是,当用户选择“
Winform
列表框
,它已经绑定到一个数据源
var custList=Cusomer.CustomerList();
lstbox.DataSource=custList;
`enter code here`
lstbox.DisplayMember="CustName";
lstbox.ValueMemebr="CustId";
现在,我想在同一个列表框中添加一个名为“All”的文本,以便将其显示为第一个列表项。此外,通过绑定添加的列表项也应存在于此处。我的想法是,当用户选择“全部”选项时,必须自动选择所有列表项
知道如何添加新的文本值吗
谢谢。使用ListBox.Items。插入并指定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();
}
当然,不要忘记设置事件处理程序:)
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);