希望这会帮助你。
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);