read a checkbox in a gridview

Hello,
I am trying to read a checkbox status from a loaded gridview from my database.  I have the gridview loaded and then I hit the Edit button to change the checkbox status.  What i want to do is read the checkbox status and then change my database accordingly.  My trouble is that I can't read the Editable status of the checkbox.  Here is how my gridview is declared in ASP.NET

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowEditing="GridView1_RowEditing" Width="396px">
                  <AlternatingRowStyle BackColor="Silver" />
                  <Columns>
                      <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
                      <asp:CheckBoxField DataField="IsApproved" HeaderText="IsApproved" SortExpression="IsApproved" />
                      <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
                      <asp:CommandField ShowEditButton="True" UpdateText="" />
                  </Columns>
</asp:GridView>

And here is my C# attempt

        GridViewRow curRow = GridView1.Rows[e.NewEditIndex];
        userName.user = curRow.Cells[2].Text;
        Boolean joke = ((CheckBox)curRow.FindControl("GridView1")).Checked;

the error I receive is: Object reference not set to an instance of an object.

Can anyone help me?  thanks!

Kevin
kevinmeredithAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dfu23Commented:
Give your asp:CheckBoxField an ID and use that in the FindControl method.
Elvio Lujan.Net Senior DeveloperCommented:
       GridViewRow curRow = GridView1.Rows[e.NewEditIndex];
        userName.user = curRow.Cells[2].Text;
        Boolean joke = ((CheckBox)curRow.FindControl(1)).Checked;
nauman_ahmedCommented:
I think

userName.user = curRow.Cells[2].Text;

should be

userName.user = curRow.Cells[1].Text;

since CheckBoxField is the second column.

--Nauman.
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

nauman_ahmedCommented:
Also I recommend you follow the approach given below:

 Boolean joke = false;
foreach(Control c in curRow.Cells[1].Controls)
{
   if (c.GetType() == typeof(CheckBox))
   {
       joke = ((CheckBox)c).Checked;
   }
}

--Nauman.
nauman_ahmedCommented:
forgot to add break:

Boolean joke = false;
foreach(Control c in curRow.Cells[1].Controls)
{
   if (c.GetType() == typeof(CheckBox))
   {
       joke = ((CheckBox)c).Checked;
       break;
  }
}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
kevinmeredithAuthor Commented:
dfu23,

How would I give it an ID?
kevinmeredithAuthor Commented:
lem2802,

That did not work.  it says the FindControl needs a string and not an int.  Thanks!
Elvio Lujan.Net Senior DeveloperCommented:
yea sorry i posted bad...

Boolean joke = ((CheckBox)curRow.Controls(1)).Checked;
also try:
Boolean joke = ((CheckBox)curRow.Controls(0)).Checked;

kevinmeredithAuthor Commented:
Nauman,
The username works fine.  I get the name each time.  Your code with the break works great!  A side question, your c.GetType().  what is that doing?  is that retrieving the type of control that is?  If i were to change the Cells[1] to another column, i could check and see what type of control that one was, correct?  thanks.  I appreciate it
kevinmeredithAuthor Commented:
sorry lem2802, neither of those worked either.  the first one had the Object error and the second was a type mismatch.  thanks for your help anyway
nauman_ahmedCommented:
Kevin:

You never know what control the datagrid cell has. Therefore its best to loop through all the control in the datagrid cell, and compare its type with the type of control you want to find and in your case in c.GetType() == TypeOf(CheckBox). If you want to find another control in another cell, you just have to input the correct column index in dg. Following the same technique, you can find control of any type.

--Nauman.
kevinmeredithAuthor Commented:
thank nauman for your help.  I have another question for you.  if you want, i can start a new thread and give you more points.  i tried moving the function to another part in the code and it won't work for me.  i thought your loop should work anywhere you have the curRow defined.  Here is my original code.

   protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridViewRow curRow = GridView1.Rows[e.NewEditIndex];
        userDetails.user = curRow.Cells[2].Text;
        foreach (Control c in curRow.Cells[1].Controls)
        {
            if (c.GetType() == typeof(CheckBox))
            {
                userDetails.isApp = ((CheckBox)c).Checked;
                break;
            }
        }
    }

and here is where i'm tyring to put it

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        MembershipUser mUser = Membership.GetUser(userDetails.user);
        GridViewRow curRow = GridView1.SelectedRow;
        string testestset = curRow.Cells[1].Controls.ToString();
        foreach (Control c in curRow.Cells[1].Controls)
        {
            if (c.GetType() == typeof(CheckBox))
            {
                userDetails.isApp = ((CheckBox)c).Checked;
                break;
            }
        }
        mUser.IsApproved = userDetails.isApp;
        Membership.UpdateUser(mUser);
    }

I know since the first had a different Event Args that the e wouldn't work the same, but i assumed that the SelectedRow should suffice.  any ideas?  like i said, i can start a new thread if you want me to.  thanks!

Kevin
nauman_ahmedCommented:
No need to start the thread :)

What error are you getting?

--Nauman.
kevinmeredithAuthor Commented:
foreach (Control c in curRow.Cells[1].Controls)

this line (and the one above it, but i should have deleted before i posted earlier) gives me this the "Object reference not set to an instance of an object." error.  any ideas on why?  thanks!
nauman_ahmedCommented:
Remove the foreach statement and type the following:

Response.Write(curRow.Cells.Count);

What output is displayed?

--Nauman.
kevinmeredithAuthor Commented:
Object reference not set to an instance of an object.

It runs into an error.  where would the response show up at?
nauman_ahmedCommented:
I think

GridViewRow curRow = GridView1.SelectedRow;


is returning null. Do you have if (!Page.IsPostBack) check in Page_Load event before you are binding the GridView?

--Nauman.
kevinmeredithAuthor Commented:
no i do not.  What is that saying?  thanks for all your help Nauman!
kevinmeredithAuthor Commented:
Hi Nauman,

I got it working with your idea of it not being set.  What I did was added the curRow to my data class and then passed it along to the Update Button event.  then I just made the curRow in that method the index of the userDetail class.  Here is the code

protected void btnUpdate_Click(object sender, EventArgs e)
    {
        MembershipUser mUser = Membership.GetUser(userDetails.user);
        GridViewRow curRow = GridView1.Rows[userDetails.gvrCur.RowIndex];
        foreach (Control c in curRow.Cells[1].Controls)
        {
            if (c.GetType() == typeof(CheckBox))
            {
                userDetails.isApp = ((CheckBox)c).Checked;
                break;
            }
        }
        mUser.IsApproved = userDetails.isApp;
        Membership.UpdateUser(mUser);
        GridViewCancelEditEventArgs ce = new GridViewCancelEditEventArgs(userDetails.gvrCur.RowIndex);
       
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridViewRow curRow = GridView1.Rows[e.NewEditIndex];
        userDetails.gvrCur = curRow;
        userDetails.user = curRow.Cells[2].Text;
        foreach (Control c in curRow.Cells[1].Controls)
        {
            if (c.GetType() == typeof(CheckBox))
            {
                userDetails.isApp = ((CheckBox)c).Checked;
                break;
            }
        }
    }

Passing the userDetails.gvrCur directly didn't catch the changes after the Edit button was hit.  this seems to work fine.  thank you so much for your extended help.

nauman_ahmedCommented:
Glad I was able to help :)

--Nauman.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.