Asp.net: Get selected items (values) of Checkboxlist

In this tutorial I am going to explain how to get selected items (values) of Checkboxlist in asp.net using C#, VB.net 

Implementation:
HTML Markup:
<fieldset>
            <legend>Get selected items (values) of Checkboxlist</legend>
            <table>
                <tr><td>Select fruit:</td><td>  <asp:CheckBoxList ID="chkfruit" runat="server" RepeatDirection="Horizontal">
            <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:CheckBoxList></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 <= chkfruit.Items.Count - 1; i++)
            {
                if (chkfruit.Items[i].Selected)
                {
                    if (selectitems == "")
                    {
                        selectitems = chkfruit.Items[i].Text;
                    }
                    else
                    {
                        selectitems += "," + chkfruit.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 chkfruit.Items.Count - 1
                If chkfruit.Items(i).Selected Then
                    If selectitems = "" Then
                        selectitems = chkfruit.Items(i).Text
                    Else
                        selectitems += "," + chkfruit.Items(i).Text
                    End If
                End If
                lblresult.Text = selectitems
            Next
        Catch ex As Exception
        End Try
    End Sub


Post a Comment

0 Comments