Search code examples
asp.netdrop-down-menulistboxpageload

How to clear all items in a ListBox, when we select other item in a DropDownList?


I have a Listbox named listbox1, a show button and a DropDownList control in my design page.

  • DropDownList contains a list of group types.

  • OnClick method of show button will fetch data based on a grouptype from DB and populate in Listbox1.

But if I select other item in DropDownList, the items in listbox are equal to previous selection. I want to clear the items before selecting another item and clicking on show button.

How to achieve that?


Solution

  • <asp:DropDownList ID="ddlGroupTypes" runat="server" OnSelectedIndexChanged="ClearListBox" AutoPostBack="true" />
    

    Your code behind:

    protected void ClearListBox(object sender, EventArgs e){
        ListBox1.Items.Clear();
    }
    

    Your show button OnClick method:

    protected void ShowButton_Click(object sender, EventArgs e){
        BindYourListBoxAsYouNeed();
    }
    

    When you will select any other item, your ListBox will be cleared. And when you will click on Show button, you have to populate your ListBox items again.

    Is this what you need?