Tim Johnson
Tim Johnson

Reputation: 81

Return Gridview Checkbox boolean

I've racked my brains on trying to access the ID column of a gridview where a user selects a checkbox:

<asp:GridView ID="gvUserFiles" runat="server">
            <Columns>
            <asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" >
                <ItemTemplate>
                    <asp:CheckBox  ID="chkSelect" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            </Columns>
        </asp:GridView>

The gridview columns are chkSelect (checkbox), Id, fileName, CreateDate

When a user checks a checkbox, and presses a button, i want to receive the "id" column value.

Here is my code for the button:

foreach (GridViewRow row in gvUserFiles.Rows)
            {
                var test1 = row.Cells[0].FindControl("chkSelect");
                CheckBox cb = (CheckBox)(row.Cells[0].FindControl("chkSelect"));
                //chk = (CheckBox)(rowItem.Cells[0].FindControl("chk1"));  
                if (cb != null && cb.Checked)
                {
                    bool test = true;

                }
            }

The cb.checked always is returned false.

Upvotes: 1

Views: 3428

Answers (2)

Mateus Schneiders
Mateus Schneiders

Reputation: 4903

The Checkboxes being always unchecked can be a problem of DataBinding. Be sure you are not DataBinding the GridView before the button click event is called. Sometimes people stick the DataBinding on the Page_load event and then it keeps DataBinding on every PostBack. As it is called before the button click, it can make direct influence. When the GridView is DataBound you lose all the state that came from the page.

If you Databind the GridView on the Page_load, wrap it verifying !IsPostBack:

if (!IsPostBack)
{
    gvUserFiles.DataSource = data;
    gvUserFiles.DataBind();
}

If that is not your case, you can try verifying the checked property based on the Request.Form values:

protected void button_OnClick(object sender, EventArgs e)
{
    foreach (GridViewRow row in gvUserFiles.Rows)
    {
        CheckBox cb = (CheckBox)row.FindControl("chkSelect");

        if (cb != null)
        {
            bool ckbChecked = Request.Form[cb.UniqueID] == "on";

            if (ckbChecked)
            {
                //do stuff
            }
        }
    }
}

The Checked value of a CheckBox is sent by the browser as the value "on". And if it is not checked in the browser, nothing goes on the request.

Upvotes: 3

Sachin
Sachin

Reputation: 40970

You can achieve it using datakey like this

Add Datakey to your gridview

<asp:GridView ID="gvUserFiles" runat="server" DataKeyNames="Id">

and get it server side like this

string value = Convert.ToString(this.gvUserFiles.DataKeys[rowIndex]["Id"]);

Upvotes: 1

Related Questions