Tuesday, October 7, 2014

Get multiple selected values from Listbox in asp.net

Introduction: In this article today I am going to explain how we can get multiple selected values from Listbox in asp.net
Description:

Design the webform as given below:
  <fieldset style="width:450px">
    <legend>Listbox Example</legend> 
    Country :
<asp:ListBox ID="lstcountry" runat="server" Width="100px" SelectionMode="Multiple">
            <asp:ListItem>India</asp:ListItem>
            <asp:ListItem>China</asp:ListItem>
            <asp:ListItem>Cuba</asp:ListItem>
            <asp:ListItem>Other</asp:ListItem>
        </asp:ListBox>
        <br /> 
        <br />
<asp:Button
            ID="btnsubmit" runat="server" Text="Get Value" onclick="btnsubmit_Click" /> 
        <asp:Label ID="lblmessage" runat="server"></asp:Label> 
    </fieldset>


On button click write the below given code (C#):
  protected void btnsubmit_Click(object sender, EventArgs e)
    {
        foreach (int i in lstcountry.GetSelectedIndices())
        {
            lblmessage.Text += lstcountry.Items[i].Value+",";
        }

    }

VB:
Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsubmit.Click
        For Each i As Integer In lstcountry.GetSelectedIndices()
            lblmessage.Text += lstcountry.Items(i).Value + ","
        Next
    End Sub

Build and run the project.

Demo:


Is this article helpful for you?
If yes post your comment to appreciate my work and fell free to contact me. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment