Asp.net: Get all selected items (values) of Listbox

In this tutorial I am going to explain how to get all selected items (values) of listbox in asp.net using C#, VB.net
  
Implementation:
HTML Markup:
<fieldset style="width:400px">
            <legend> Get all selected items (values) of Listbox </legend>
            <table>
                <tr><td>Select Item: </td><td> <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" Height="100px">
                <asp:ListItem>Apple</asp:ListItem>
            <asp:ListItem>Orange</asp:ListItem>
            <asp:ListItem>Mango</asp:ListItem>
            <asp:ListItem>Pine apple</asp:ListItem>
            <asp:ListItem>Grapes</asp:ListItem>
           </asp:ListBox></td></tr>
                <tr><td>Selected Items are:</td><td>
                    <asp:Label ID="lblresult" runat="server"></asp:Label></td></tr>
                <tr><td></td><td>

                    <asp:Button ID="btnsubmit" runat="server" Text="Submit"/></td></tr>
            </table>
        </fieldset>
On button click right the below given code:
C# code:
protected void btnsubmit_Click(object sender, EventArgs e)
    {
        try
        {
            String selectitems = "";
            for (int i = 0; i <= ListBox1.Items.Count - 1; i++)
            {
                if (ListBox1.Items[i].Selected)
                {
                    if (selectitems == "")
                    {
                        selectitems = ListBox1.Items[i].Text;
                    }
                    else
                    {
                        selectitems += "," + ListBox1.Items[i].Text;
                    }
                }
                lblresult.Text = selectitems;
            }
        }
        catch (Exception ex)
        { }
    }

VB.net Code:
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
        Try
            Dim selectitems As [String] = ""
            For i As Integer = 0 To ListBox1.Items.Count - 1
                If ListBox1.Items(i).Selected Then
                    If selectitems = "" Then
                        selectitems = ListBox1.Items(i).Text
                    Else
                        selectitems += "," + ListBox1.Items(i).Text
                    End If
                End If
                lblresult.Text = selectitems
            Next
        Catch ex As Exception
        End Try

    End Sub

Post a Comment

0 Comments