1
votes

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?

2

2 Answers

1
votes

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;
    }
0
votes

If you want to clear the selected item, you should set ComboBox.SelectedIndex property to -1

http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedindex%28v=vs.110%29.aspx