Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have an gridview and checkbox on every row of an gridview.I want to get the id of selected checkbox row.so, i am trying following code
C#
foreach (GridViewRow gvr in grdReports.Rows)
       {
           CheckBox chkSelectEmp = (CheckBox)grdReports.FindControl("chkSelect");
           Label lblEmpId = (Label)grdReports.FindControl("lblEmpRefId");
           if (chkSelectEmp.Checked == true)
               Session["EmpRefId"] = lblEmpId.Text.ToString();
       }

but getting following error
Object reference not set to an instance of an object.
on
if (chkSelectEmp.Checked == true)
Posted
Updated 28-Mar-14 23:12pm
v2

try this
C#
foreach (GridViewRow row in grdReports.Rows)
{ 
CheckBox chkSelectEmp = row.FindControl("chkSelect") as CheckBox;
if (chkSelectEmp .Checked == true)
{
Label lblEmpId = (Label )grdReports.Rows[rowIndex].Cells[6].FindControl("lblEmpRefId");
Session["EmpRefId"] = lblEmpId.Text.ToString(); 
}
}

here , you metion Cells[6] to Correct Index of "LblEmpRefId"
 
Share this answer
 
v3
replace code grdReports to row when use findcontrol for label and checkbox .

try this
C#
foreach (GridViewRow row in grdReports.Rows)
            {

                CheckBox chkSelectEmp = row.FindControl("chkSelect") as CheckBox;
                
                if (CheckBox1.Checked == true)
                {
                   Label lblEmpId = row.FindControl("lblEmpRefId") as Label;
                   Session["EmpRefId"] = lblEmpId.Text.ToString();

                }
            }
 
Share this answer
 
v2
change
grdReports.FindControl

to
gvr.FindControl
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900