lundi 18 janvier 2016

How to save checkbox for each row in GridView?

I have a GridView that displays a list of checklist items and next to each of these items is a checkbox. enter image description here

Code for GridView:

    <asp:GridView  style="width:75%"  
                        ID="gvCVRTDetails" 
                        ShowHeaderWhenEmpty="true"
                        CssClass="tblResults" 
                        runat="server" 
                        OnRowDataBound="gvCVRTDetails_RowDataBound"                             
                        DataKeyField="ID" 
                        AutoGenerateColumns="false"
                        allowpaging="false"
                        AlternatingRowStyle-BackColor="#EEEEEE">
                        <HeaderStyle CssClass="tblResultsHeader" />
                        <Columns>
                            <asp:BoundField DataField="Description" HeaderText="Checklist Items"></asp:BoundField> 
                            <asp:TemplateField HeaderText ="Checked?" ItemStyle-HorizontalAlign="Center">
                                <ItemTemplate>
                                         <asp:CheckBox ID="chkChecked" runat="server"></asp:CheckBox>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

protected void gvCVRTDetails_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            lookupCVRT work = (lookupCVRT)e.Row.DataItem;
            GridView gv = sender as GridView;
            e.Row.Attributes.Add("ID", "gvCVRTDetails_" + work.ID);
            e.Row.Cells[0].Attributes.Add("onclick", "event.stopPropagation();");

            HtmlGenericControl lnkShowHide = (HtmlGenericControl)e.Row.FindControl("lnkShowHide");
            HyperLink ChecklistItem = (HyperLink)e.Row.FindControl("ID");

            CheckBox chkChecked = e.Row.FindControl("chkChecked") as CheckBox;

            chkChecked.Checked = work.Checked;

        }
    }

The problem is when I try call the checkbox in the function that saves the changes to the database I get the error: the name chkChecked doesn't exist.

Code to save to database:

foreach (lookupCVRT work in worknew)
                {

                    int tmpParentID = work.ID;
                    if (ParentID.HasValue)
                        tmpParentID = ParentID.Value;

                    work.VehicleID = ParentID.Value;
                    work.ChecklistDate = DateOfWork.Value;
                    work.User = CurrentUser.Username;
                    work.Checked = chkChecked.Checked; //Error here

                    work.Update();
              } 

So how do I call the checkbox from the GridView?




Aucun commentaire:

Enregistrer un commentaire