1

I'm adding checkbox controls dynamically in asp.net gridview like this:

CheckBox cb1 = new CheckBox();
cb1.Text = row.Cells[3].Text;
row.Cells[3].Controls.Add(cb1);    

And I want to access whether that checkbox is checked or not on button click event...

on button click I have tried this:

foreach (GridViewRow item in grdreport.Rows)
{
    if (item.RowType == DataControlRowType.DataRow)
    {
        CheckBox checkbox1 = (CheckBox)item.FindControl("cb1");
        // cb1.Checked = true;
        if (checkbox1.Checked)
        {
        }
    }
}

but it gives me an error:

Object reference not set to an instance of an object cb1 value is null

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Hi @Nivas. When you run your program , right click on page and look at source , or use similar tool to do so. You will be able to verify what name your control actually has. – Alicia Jan 23 '19 at 10:57
  • @Alicia after inspect page the control name show is cb1 – Nivas Khatal Jan 23 '19 at 11:10

3 Answers3

0
foreach (GridViewRow row in grdreport.Rows)
{

    CheckBox checkbox1= (row.Cells[3].FindControl("cb1") as CheckBox);
    if (checkbox1.Checked)
                        {

                        }
}

There is a need to access the checkbox trough a specific row and cell

SomethingCool
  • 303
  • 2
  • 20
0

Focus on this line:

 CheckBox checkbox1 = (CheckBox)item.FindControl("cb1");

First check if item.FindControl("cb1") is giving you any value or not. More Info - Object Reference Exception

Sahil Sharma
  • 1,813
  • 1
  • 16
  • 37
0

When checkbox or any object is added dynamically to Gridview during RowDataBound(), and if the value of that dynamic object should be retrieved on button click, enable view state for that object during RowDataBound() and it works like a charm.

CheckBox cb1 = new CheckBox();
cb1.Text = row.Cells[3].Text;
**cb1.EnableViewState = true;**
row.Cells[3].Controls.Add(cb1);
Vasanth
  • 128
  • 1
  • 18