GridView 中的 CheckBoxField 不会绑定到数据库中的字符串字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/341807/
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
CheckBoxField in GridView won't bind to a string field in the database
提问by minty
How do I bind a CheckBoxField in my GridView to an underlying db field that is a string. The string is either "1" or "0" but all the same the GridView won't willingly bind to it. What do I do. What is the best way to have a checkbox in the GridView and have it get and set the string in the database (or the underlying datasource).
如何将 GridView 中的 CheckBoxField 绑定到作为字符串的底层数据库字段。该字符串是“1”或“0”,但 GridView 不会愿意绑定到它。我该怎么办。在 GridView 中有一个复选框并让它在数据库(或底层数据源)中获取和设置字符串的最佳方法是什么。
回答by Andrew Rollings
The CheckBoxField binds to a boolean. You can either convert the string to a boolean in the binding expression, or cast it in the db return.
CheckBoxField 绑定到一个布尔值。您可以在绑定表达式中将字符串转换为布尔值,或者在 db 返回中将其转换。
It would make more sense for the database to store the checkbox state as a bit rather than a string. Then this problem would go away completely.
数据库将复选框状态存储为位而不是字符串会更有意义。那么这个问题就会完全消失。
Of course, if you need to store the third 'grayed' state, that complicates matters slightly, but you could still store the state as an int.
当然,如果您需要存储第三个“灰色”状态,这会使问题稍微复杂化,但您仍然可以将状态存储为 int。
回答by BenAlabaster
This should work:
这应该有效:
Checked='<%# DataBinder.Eval(Container.DataItem, "MyStringField") = "1" %>'
Normally a checkbox value would be mapped to a bit value in your database so you wouldn't get this issue.
通常,复选框值会映射到数据库中的位值,因此您不会遇到此问题。
回答by sougata mukherjee
I was working in VB and I tried something like this
我在 VB 中工作,我尝试过这样的事情
<asp:checkbox runat="server" id="chkCastCool" enabled="false"
checked='<%CType(DataBinder.Eval(Container.DataItem,"Cast_Cool").ToString().Replace("Y","True").Replace("N","False"),Boolean)%>'/>