How to get checkbox value with in asp.net using C#

How to get checkbox value example in asp.net using C#. In this article, we will learn How to get check box value with example in asp.net using C#.

What is Checkbox?

A CheckBox control allows users to select single or multiple items from a list of items. It is use to get multiple inputs from the user and allows users to select choices from the set of choices. It takes user input in a yes or no format. To create CheckBox we can drag it from the toolbox in visual studio.

This is a server-side control and ASP.NET provides its own tag to create it. Below is the example.

< asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>

The server renders it as the HTML control and produces the following code to the browser.

< input id="CheckBox2" type="checkbox" name="CheckBox2" /><label for="CheckBox2">J2EE</label>

How to get selected value from the checkbox?

If we want to get the selected value of checkboxes, we have to understand it from an example. we need to pass the checked value in a string with comma separation and count how many boxes are checked. An example is given below:

When only 1 box is checked result will be:

Swimming

Count=1

When 3 boxes are checked result will be:

Swimming,Dancing,Singing

Count = 3 

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="HobbyId">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Hobby" HeaderText="Hobby" ItemStyle-Width="150px" />
    </Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
<asp:Label ID="lblMessage" runat="server" />
Namespaces

C# Code to get Selected Value from CheckBox

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Hobby], [IsSelected] FROM Hobbies"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
 
protected void Save(object sender, EventArgs e)
{
    string hobbyName = string.Empty;
    int count = 0;
    foreach (GridViewRow row in GridView1.Rows)
    {
        bool isSelected = (row.FindControl("chkSelect") as CheckBox).Checked;
        if (isSelected)
        {
            hobbyName += row.Cells[1].Text + ",";
            count++;
            lblMessage.Text = "Hobbies are : " + hobbyName.TrimEnd(',') + "<br/>Count =  " + count;
        }
    }
}

Code for a button event that will show the selected values of checkbox

If you have a set of input checkboxes without a name and you would like to get the values from gridview of those that you have only checked so the below code should be written on a button event. If you didn’t understand from the above example so the simple code is written below which you have to write on a button.

protected void BtnAdd_Click(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in GvModules.Rows)
    {
        CheckBox chk = (CheckBox)gvr.FindControl("ChkAdd");

        if (chk.Checked == true)
        {
           // do something here if checkbox is checked

        }
    }
}

This code will show all selected values of checkboxes when the button is clicked.

In this way, we can get the selected value from the checkbox in ASP.NET using C#.