Wednesday, March 16, 2011

CheckBoxField in GridView won't bind to a string field in the database

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

From stackoverflow
  • 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.

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

    minty : Almost; You got me on the right track:
    Andrew Rollings : 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 :)
    BenAlabaster : 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.
    minty : 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.
    BenAlabaster : Isn't it amazing the hoops that .NET makes you jump through... :)

0 comments:

Post a Comment