无法绑定Gridview中的复选框

时间:2016-01-26 15:48:11

标签: c# asp.net gridview checkbox

我有一个显示列表的GridView,用户可以为每个项目选中一个复选框。

enter image description here

例如,我检查第二行。我可以在数据库中看到此描述旁边的检查值已更新为1:

enter image description here

但是当我回到GridView时,所有复选框都是空白的。

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="ChecklistID" HeaderText="ID" ></asp:BoundField> 
                            <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();");

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

            if(work.Checked)
            {
                chkChecked.Checked = true;
            } 

        }
    }

如果数据库中的Checked字段有值但我没有工作,我尝试设置chkChecked.Checked = true;。如果数据库中的值等于1,如何将复选框显示为勾选?

绑定网格:

 protected void gridviewParent_SelectedIndexChanged(object sender, EventArgs e)
    {
        List<lookupCVRT> workDetails = lookupCVRT.GetChecklistItemsByChecklistID(Company.Current.CompanyID, ParentID.ToString(), gvCVRT.SelectedDataKey.Value.ToString());
        gvCVRTDetails.DataSource = workDetails;
        gvCVRTDetails.DataBind();
        FireJavascriptCallback("setArgAndPostBack ();");

    }

1 个答案:

答案 0 :(得分:0)

您应该将复选框绑定到从db读取的属性,例如:

     <asp:TemplateField HeaderText ="Checked?" ItemStyle-HorizontalAlign="Center">
              <ItemTemplate>
              <asp:CheckBox ID="chkChecked"  Checked='<%# Bind("YourCheckPropertyFromModel") %>'runat="server" ></asp:CheckBox>
              </ItemTemplate>
     </asp:TemplateField>