3

I have to bind datarows to my controls. So far so good. The problem now is, that my datarow contains only strings in the column I have to bind, but of course the property "checked" of a Checkbox takes only boolean arguments.

Is there a way to use DataBinding here? Maybe with some kind of converter in between?

Thanks

lostiniceland
  • 3,729
  • 6
  • 38
  • 50
  • What are you using as a string representation of the boolean value? 'True'/'False'? '1'/'0'? Some code might help, preferably the code in which you bind the controls. – Phaedrus May 04 '09 at 17:35

1 Answers1

11

Use the ConvertEventHandler Delegate to change types for DataBinding.

Example

    Binding binding = new Binding("checked", dt, "string_field");
    binding.Format += new ConvertEventHandler(binding_Format);
    binding.Parse += new ConvertEventHandler(binding_Parse);
    this.checkbox1.DataBindings.Add(binding); 

    void binding_Format(object sender, ConvertEventArgs e)
    {
        if (e.Value.ToString() == "yep") e.Value = true;
        else e.Value = false;
    }

    void binding_Parse(object sender, ConvertEventArgs e)
    {
        if ((bool)e.Value) e.Value = "yep";
        else e.Value = "nope";
    }
Jeff Hall
  • 1,694
  • 11
  • 7
  • Thanks a lot. But still one question. Will the ConvertEventHandler also transform my values back into the string when it goes down to the database. I mean, DataBinding is meant to cover both ways. – lostiniceland May 05 '09 at 10:57
  • Yes it can transform back to string using the Parse event. I have updated the example to show this. – Jeff Hall May 05 '09 at 13:53
  • 1
    Great thanks. But one comment: you have to set the formattingEnabled, otherwise the Format-event is never called. Binding binding = new Binding("checked", dt, "string_field", true); works – lostiniceland May 05 '09 at 16:03
  • Is it possible to bind a checkbox to an int rather than a string? Specifically, I want to bind it so that when the checkbox is checked, the field is set to 100 and when it's cleared the field is set to 0. – Ron Inbar Jul 12 '17 at 11:59