user8512043
user8512043

Reputation: 1157

CheckBox Doesn't Get Checked in ASP.NET GridView

I've a project where I am trying to check CheckBox control in a GridView. Unfortunately whenever I do so, it never gets checked and returns false every time. So here is the code that I tried so far:

ASP.NET

<asp:GridView ID="grdAssignMenu" runat="server" AutoGenerateColumns="False" CssClass="custListTBL" Height="298px" Width="324px">
      <Columns>
            <asp:TemplateField>
                  <ItemTemplate>
                       <asp:CheckBox ID="chkControl" runat="server" />
                  </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Menu Name">
                  <ItemTemplate>
                       <asp:Label ID="lblMenu" runat="server" Text='<%# Eval("roleName").ToString() %>'></asp:Label>
                  </ItemTemplate>
            </asp:TemplateField>
      </Columns>
</asp:GridView>

C#

protected void btnSave_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in grdAssignMenu.Rows)
    {
        System.Web.UI.WebControls.CheckBox cb = (System.Web.UI.WebControls.CheckBox)row.FindControl("chkControl");
        bool status = cb.Checked;

        if (cb.Checked) //Returns false every time, even though checked
        {
           System.Web.UI.WebControls.Label lbl = (System.Web.UI.WebControls.Label)row.FindControl("lblMenu");
           string lblValue = lbl.Text;

           lblMsg.Text = lblValue;
        }
    }
}

Basically I want to retrieve associated data from the CheckBox that are checked and sure that the above code is the working one. But stuck and any suggestion is highly appreciable.

Upvotes: 2

Views: 1899

Answers (1)

Ratan
Ratan

Reputation: 101

Please try using the (!IsPostBack) before you are binding the gridview, if not already. It might be possible that your gridview is refreshed each time the aspx page postbacks to code. Also if this doesn't help then please share the pageload code or the code where you are binding the gridview.

Upvotes: 4

Related Questions