Reputation: 41
I have c# Winform
Listbox
that is already been bound to a data source
.
var custList=Cusomer.CustomerList();
lstbox.DataSource=custList;
`enter code here`
lstbox.DisplayMember="CustName";
lstbox.ValueMemebr="CustId";
Now I want to add a text called "All" to the same list box
so that it should be displayed as the first listitem
. Also the list items added through binding
should also be present there. My idea is when the user selects the "ALL" option all of the list items has to be selected automatically.
Any idea how I can add the new text value?
Thanks.
Upvotes: 3
Views: 3027
Reputation: 612
hope this will help you.
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();
}
And if you want to select all customer when the user select ALL, add this method:
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);
}
}
Off course, don't forget to set the event handler :)
this.lstbox.SelectedIndexChanged += new System.EventHandler(this.lstbox_SelectedIndexChanged);
Upvotes: 0
Reputation: 70718
Use ListBox.Items.Insert
and specify 0
as the index.
ListBox1.Items.Insert(0, "All");
Upvotes: 2