我已将c#Winform
Listbox
绑定到data source
。
var custList=Cusomer.CustomerList();
lstbox.DataSource=custList;
`enter code here`
lstbox.DisplayMember="CustName";
lstbox.ValueMemebr="CustId";
现在我想将一个名为“All”的文本添加到同一list box
,以便它应显示为第一个listitem
。此外,通过binding
添加的列表项也应该存在。我的想法是当用户选择“全部”选项时,必须自动选择所有列表项。
知道如何添加新文本值吗?
感谢。
答案 0 :(得分:2)
使用ListBox.Items.Insert
并指定0
作为索引。
ListBox1.Items.Insert(0, "All");
答案 1 :(得分:0)
希望这会对你有所帮助。
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);