Add items to listbox programmatically in asp.net

In this article I am going to explain how to add items to listbox programmatically in asp.net

Implementation:

HTML Markup:
<fieldset style="width:400px">
            <legend>Add items to Listbox </legend>
           <asp:ListBox ID="ListBox1" runat="server" Visible="false" SelectionMode="Multiple"></asp:ListBox>
            <br />
        Add Options: <asp:TextBox ID="txtoption" runat="server"></asp:TextBox><asp:Button ID="btnoption" runat="server" Text="btnsubmit" OnClick="btnoption_Click" />
        </fieldset>

Add items to Listbox
C# Code:
protected void btnoption_Click(object sender, EventArgs e)
    {
        ListBox1.Visible = true;
        ListBox1.Items.Add(new ListItem(txtoption.Text));
        txtoption.Text = string.Empty;
    }

VB.net Code:
Protected Sub btnoption_Click(sender As Object, e As EventArgs) Handles btnoption.Click
        ListBox1.Visible = True
        ListBox1.Items.Add(New ListItem(txtoption.Text))
        txtoption.Text = String.Empty

    End Sub

Post a Comment

0 Comments