Search code examples
c#asp.netlistboxdropdownbox

Added Items multiply (Listbox / Dropdownbox)


I have a couple of Listboxes, and want to add Items to it. So I have a Button and a Listbox:

<asp:ListBox ID="ListBox1" runat="server" Rows="5"></asp:ListBox>    
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />

And I add Items to the Listbox in the C# Code:

for (i = 0; i < getSurnameData.countData; i++)
{
     ListBox1.Items.Insert(i, getSurnameData.StringData[i]);  //Writes the Outcome into a Listbox
}

The problem is, that if I press the Button, the Page reloads and the Items get added again, and again. This leads to a massive Listbox, the more I press the Button.

Any Ideas how I can prevent that?


Solution

  • On each button click first you should clear the content of list box using below code

    listbox1.Items.Clear();
    

    If it didn't cleared it will append the data to the existing values of listbox.

    in your case the for loop is adding values to the listbox so before the for loop do the coding

    listbox1.Items.Clear();
    for (i = 0; i < getSurnameData.countData; i++)
    {
     ListBox1.Items.Insert(i, getSurnameData.StringData[i]);  
    }