views:

500

answers:

2

Hello everyone

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

A: 

What is it in the datarow that determines whether the cb should be checked or not? Is it, if the cell's value is not DBNULL.value?

aape
+4  A: 

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
Now THAT'S handy! :) +1
roosteronacid
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
Yes it can transform back to string using the Parse event. I have updated the example to show this.
Jeff Hall
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