Reputation: 371
i am working on windows form application..
i have two combo box..i changed my combo box drop down style
property to DropDownList
after saving the data i want to clear item in the combo box..so i given code like this:
CmbDepartment.Text = "";
cmbvisitpurpose.Text = "";
but this is not clearing the selected item from my combobox..so i changed code like this:
cmbvisitpurpose.Items.RemoveAt(cmbvisitpurpose.SelectedIndex = -1)
CmbDepartment.Items.RemoveAt(CmbDepartment.SelectedIndex = -1)
this is permenantly removing particular item from my combobox..if i want to get all item in the combbox..agian i want to load the page..i want to just clear the selected item.. how i can do this?
Upvotes: 1
Views: 11441
Reputation: 27
one way to do this is:
ComboBox1.SelectedItem = null;
I guess this method removes not only the text but the whole item.
Upvotes: 0
Reputation: 222657
This will only remove from the combobox, not from the datasource.
If you want to retain the items, better use a local collection.
CmbDepartment.Items.Remove(CmbDepartment.SelectedItem);
Here is a sample on how to assig values to collection
List<string> DepartmentsPermanent;
List<string> DepartmentsTemporary;
public Form1()
{
InitializeComponent();
DepartmentsPermanent = new List<string>();
DepartmentsPermanent.Add("EEE");
DepartmentsPermanent.Add("CSE");
DepartmentsPermanent.Add("E&I");
DepartmentsPermanent.Add("Mechanical");
comboBox1.DataSource = DepartmentsPermanent;
//here you assign the values to other List
DepartmentsTemporary = DepartmentsPermanent.ToList();
}
//Now if you have selected EEE from the list and you want to remove on selection
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem != null && DepartmentsTemporary != null)
{
DepartmentsTemporary.Remove(comboBox1.SelectedItem.ToString());
comboBox1.DataSource = DepartmentsTemporary;
}
//If you want to assign the default values again you can just assign the PermanentList
//comboBox1.DataSource = DepartmentsPermanent;
}
Upvotes: 1
Reputation: 3816
If you want to clear the selected item, you should set ComboBox.SelectedIndex
property to -1
Upvotes: 0