[c#] Gridview get Checkbox.Checked value

I have a GridView that has 10 columns populated by CheckBoxes. But instead of using FindControl() is there a way to get the CheckBox.Checked value by using a loop?

Current Code:

if (e.CommandName == "updaterow")
{
     int index = Convert.ToInt32(e.CommandArgument);
     GridViewRow selectedRow = GridView1.Rows[index];
     // TableCell BranchCode = selectedRow.Cells[0];
     CheckBox cb101 = (CheckBox)selectedRow.FindControl("cb101");
     CheckBox cb102 = (CheckBox)selectedRow.FindControl("cb102");
     //...and so on
}  

ASPX CODE:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="101">
            <ItemTemplate>
                <asp:CheckBox runat="server" id="cb101" AutoPostBack="false" Checked='<%# Eval("101").ToString()=="1" ? true : false %>' Enabled='<%#(String.IsNullOrEmpty(Eval("101").ToString()) ? false: true) %>'/>
            </ItemTemplate>
        </asp:TemplateField>
        ....and so on
        <asp:ButtonField ButtonType="Button" CommandName="updaterow" Text="Update"/>
    </Columns>
</asp:GridView>

This question is related to c# asp.net visual-studio-2010

The answer is


Try this,

Using foreach Loop:

foreach (GridViewRow row in GridView1.Rows)
{
     CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
     if (chk != null && chk.Checked)
     {
       // ...
     }
}

Use it in OnRowCommand event and get checked CheckBox value.

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];

    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox chkbox = (CheckBox)row.FindControl("CheckBox1");
        if (chkbox.Checked == true)
        {
            // Your Code
        }
    }

     foreach (DataRow row in DataRow row in GridView1.Rows)
        {
            foreach (DataColumn c in GridView1.Columns)

               bool ckbVal = (bool)(row[c.ColumnName]);

        }

Blockquote

    foreach (GridViewRow row in tempGrid.Rows)
    {
        dt.Rows.Add();
        for (int i = 0; i < row.Controls.Count; i++)
        {
            Control control = row.Controls[i];
            if (control.Controls.Count==1)
            {
                CheckBox chk = row.Cells[i].Controls[0] as CheckBox;
                if (chk != null && chk.Checked)
                {
                    dt.Rows[dt.Rows.Count - 1][i] = "True";
                }
                else
                dt.Rows[dt.Rows.Count - 1][i] = "False";
            }
            else
                dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text.Replace("&nbsp;", "");
        }
    }

For run all lines of GridView don't use for loop, use foreach loop like:

foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
    if (row.RowType == DataControlRowType.DataRow)
    {
         CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);

         if (chkRow.Checked)
         {
              //if checked do something
         }
    }
}

If you want a method other than findcontrol try the following:

 GridViewRow row = Gridview1.SelectedRow;
 int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
 CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this

You want an independent for loop for all the rows in grid view, then refer the below link

http://nikhilsreeni.wordpress.com/asp-net/checkbox/

Select all checkbox in Gridview

CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
    cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);

    cb.Checked = ((CheckBox)sender).Checked;
}

Select checked rows to a dataset; For gridview multiple edit

CheckBox cb = default(CheckBox);

foreach (GridViewRow row in grdforumcomments.Rows)
{
    cb = (CheckBox)row.FindControl("cbsel");
    if (cb.Checked)
    {
        drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
        drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
        drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
    }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to visual-studio-2010

variable is not declared it may be inaccessible due to its protection level SSIS Excel Connection Manager failed to Connect to the Source This project references NuGet package(s) that are missing on this computer Gridview get Checkbox.Checked value error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop? Attach (open) mdf file database with SQL Server Management Studio What is and how to fix System.TypeInitializationException error? Could not load file or assembly "Oracle.DataAccess" or one of its dependencies IIS error, Unable to start debugging on the webserver