C# 如何将gridview上的复选框值与数据库表的值绑定?
我有一个bit类型的数据表列staff。在我的网格视图中,我添加了一个复选框项模板。如果在数据绑定上staff列的值=1,我想显示选中的复选框。其他明智的选择。。从搜索结果来看,我是这样写的C# 如何将gridview上的复选框值与数据库表的值绑定?,c#,asp.net,gridview,C#,Asp.net,Gridview,我有一个bit类型的数据表列staff。在我的网格视图中,我添加了一个复选框项模板。如果在数据绑定上staff列的值=1,我想显示选中的复选框。其他明智的选择。。从搜索结果来看,我是这样写的 <ItemTemplate> <asp:CheckBox ID="chk1" runat="server" Checked='<%# bool.Parse(Eval("staff").ToString()) %>'/> </ItemTemplate
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server" Checked='<%# bool.Parse(Eval("staff").ToString()) %>'/>
</ItemTemplate>
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT id,staff FROM staff_details ", con1);
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
但它显示了一个错误System.FormatException:字符串未被识别为有效的布尔值。请帮助ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Staff">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Eval("staff") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
测试和工作:
更新1
是的,我已将其设置为位类型。但显示了与查询相同的错误@Samiey Mehdimy。。它应该类似于选择id,当“1”时CASTCASE staff,然后在staff_details中选择1或0作为staff结束,con1@Samiey Mehdii如果您的staff数据库字段类型为bit,则只需使用select id、castcoalesce[staff],0和'staff'一样的位,之后您就不必担心空值了。检查我的答案,然后运行并测试
protected void Button1_Click(object sender, EventArgs e)
{
string conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\website\w2\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
SqlConnection con1 = new SqlConnection(conStr);
con1.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT id,staff FROM staff_details ", con1);
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con1.Close();
}
Checked='<%#Convert.ToBoolean(Eval("staff")) %>'
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server" Checked='<%#Convert.ToBoolean(Eval("staff")) %>' />
</ItemTemplate>