SkyeBoniwell
SkyeBoniwell

Reputation: 7122

get asp:checkbox status in gridview

I have setup up a gridview to contain a column of checkboxes like this:

                    <asp:TemplateField HeaderText = "Editor">
                        <ItemTemplate>
                             <asp:CheckBox ID="chkRemove" runat="server" AutoPostBack="false" Checked='<%#currentMember(Eval("GroupID")) %>' />
                        </ItemTemplate>
                    </asp:TemplateField>

The function, currentMember, returns true or false.

The user will be able to uncheck rows to remove the member status.

Now, once the user hits submit, how do I determine which rows the user has unchecked so I can update the database?

Upvotes: 1

Views: 1051

Answers (3)

Piotr Kula
Piotr Kula

Reputation: 9841

This does the same as the accepted answer but uses C# programming convention. The accepted answer uses the C/C++ convention also used in Java. It is not wrong but it is frowned upon.

 protected void Button1_Click(object sender, EventArgs e)
        {
            GridViewRowCollection rows = ItemsGridView.Rows;

            foreach (GridViewRow gvr in rows){
                CheckBox chk = (CheckBox)gvr.FindControl("chkremove");
                if (chk.Checked)
                {
                    //Do stuff here
                }
            }
        }

Upvotes: 1

Tariqulazam
Tariqulazam

Reputation: 4585

Put the following code in your submit button click handler

for (int i = 0; i < gridView.Rows.Count; i++)
{
    CheckBox cbox = (CheckBox)gridView.Rows[i].FindControl("chkRemove");
    if(cbox.Checked){
        //DO DATABASE STUFF
    }
}   

Upvotes: 2

Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23094

In you event handler code, go through the following steps

Get the rows:

GridViewRow row = GridView1.Rows

Then, for each row, find the CheckBox control:

CheckBox checkBox = row.FindControl("chkRemove")

See if the control was unchecked:

checkBox.Checked == false

Finally, collect the record ID that you have bound as a data key to the GridView:

int id = (int)GridView1.DataKeys[row.RowIndex].Value;

Now you should have the information you need to update your database

Upvotes: 1

Related Questions