views:

4174

answers:

2

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).

+2  A: 

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.

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.

Andrew Rollings
+4  A: 

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.

BenAlabaster
Almost; You got me on the right track:<EditItemTemplate> <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Convert.ToBoolean( Convert.ToInt32(DataBinder.Eval(Container.DataItem, "MyStringField"))) %>' /></EditItemTemplate>
minty
You shouldn't need the inner Convert, should you?Also you could do:Checked = '"1" == DataBinder.Eval(Container.DataItem, "MyStringField")' for the same effect :)
Andrew Rollings
(adding the correct <%# %> that I missed out, of course :)
Andrew Rollings
Well, theoretically, Boolean.Parse shouldn't be parsing string values, but the DataBinder.Eval should (again) theoretically convert it to a type that Boolean.Parse should be able to read that.Checked='<%# DataBinder.Eval(Container.DataItem, "MyStringField") = "1" %>' should work too.
BenAlabaster
the compiler was happiest with:Checked='<%# (string)DataBinder.Eval(Container.DataItem, "NETWORK_READ_FLAG") == "1" %>' I needed the == for c# and the cast to string so I did a value comparison instead of a reference comparison.
minty
Isn't it amazing the hoops that .NET makes you jump through... :)
BenAlabaster