C# 如何将gridview上的复选框值与数据库表的值绑定?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18482132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to bind check box values on gridview with the values of database table?
提问by ARATHY
I have a data table column "staff" of type bit. In my grid view i have added an item template of check boxes. I wants o display the check boxes checked if the value of "staff" column =1 on data bind. other wise unchecked.. from searches i have written like this
我有一个 bit 类型的数据表列“员工”。在我的网格视图中,我添加了一个复选框项目模板。如果数据绑定上“staff”列的值=1,我想显示选中的复选框。其他明智的未检查......从我这样写的搜索中
<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();
but it shows an error "System.FormatException: String was not recognized as a valid Boolean." please help
但它显示错误“System.FormatException:String 未被识别为有效的布尔值。” 请帮忙
采纳答案by Samiey Mehdi
ASPX:
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" />
Code behind:
后面的代码:
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();
}
回答by Ahmed Alaa El-Din
Tested and works :
测试和工作:
#UPDATE1
#更新1
Checked='<%#Convert.ToBoolean(Eval("staff")) %>'
<ItemTemplate>
<asp:CheckBox ID="chk1" runat="server" Checked='<%#Convert.ToBoolean(Eval("staff")) %>' />
</ItemTemplate>