[英]Grid View Checkbox Checked Off Database Value
I get an error of 我得到一个错误
Specified cast is not valid
指定的演员表无效
when I try to run my syntax. 当我尝试运行语法时。 What I am wanting to do is if the value in the database is yes check the checkbox, if it is no, then do not check the checkbox.
我要执行的操作是,如果数据库中的值为“是”,请选中该复选框;如果为“否”,则不要选中该复选框。 Here is my HTML that shows how I am trying to do such:
这是我的HTML,显示了我如何尝试这样做:
<asp:GridView runat="server" ID="dg123" AutoGenerateColumns="false" CssClass="DataGrids" GridLines="Both" ShowFooter="true">
<FooterStyle CssClass="DataGridFooters" /><HeaderStyle CssClass="DataGridHeaders" />
<Columns>
<asp:BoundField DataField="abc" HeaderText="Alpha" />
<asp:BoundField DataField="efg" HeaderText="Echo" />
<asp:TemplateField>
<ItemTemplate><asp:CheckBox ID="Completed" runat="server" Checked='<%#Eval ("Completed") %>'/></ItemTemplate>
</asp:TemplateField>
</Columns>
Where in the example above, abc
efg
and Completed
are all fields in the database. 在上面的示例中,
abc
efg
和Completed
是数据库中的所有字段。
You have to make following changes to make this work. 您必须进行以下更改才能使此工作。
I am assuming that the data item Completed
has a value of either yes
or no
. 我假设数据项
Completed
的值为yes
或no
。
Add following method to code-behind. 将以下方法添加到代码隐藏中。 This method returns a boolean value corresponding to string value of
yes
or no
. 此方法返回一个布尔值,该值对应于字符串值
yes
或no
。 This method must return a boolean type else you will get cast exception, since the property you are binding to ie Checked
is of boolean type. 该方法必须返回一个布尔类型,否则您将获得强制转换异常,因为您要绑定的属性(即
Checked
是布尔类型)。
public bool GetBoolValue(string val) { if (val.ToLower() == "yes") { return true; } else { return false; } return false; }
In your markup, change the markup for checked box to what is given below. 在您的标记中,将复选框的标记更改为下面给出的标记。
<ItemTemplate> <asp:CheckBox ID="Completed" runat="server" Checked='<%# GetBoolValue(Eval("Completed").ToString()) %>'/> </ItemTemplate>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.