Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a ValueConverter with Databinding in Winforms

In WPF it is easy to use a ValueConverter to format values etc, (in our case convert some numbers into a different unit, e.g km to miles)

I know it can be done in Winforms, but all my Googleing just brings up results for WPF and Silverlight.

like image 255
Ian Ringrose Avatar asked Apr 16 '10 12:04

Ian Ringrose


People also ask

What is Data Binding in Winforms?

Simple data binding is the type of binding typical for controls such as a TextBox control or Label control, which are controls that typically only display a single value. In fact, any property on a control can be bound to a field in a database. There's extensive support for this feature in Visual Studio.

What is value converter in WPF?

A Value Converter functions as a bridge between a target and a source and it is necessary when a target is bound with one source, for instance you have a text box and a button control. You want to enable or disable the button control when the text of the text box is filled or null.


1 Answers

You can use a TypeConverter if you're able and willing to decorate the data source property with a custom attribute.

Otherwise you have to attach to the Parse and Format events of a Binding object. This, unfortunately, eliminates using the designer for your binding for all but the simplest scenarios.

For example, let's say you wanted a TextBox bound to an integer column representing kilometers and you wanted the visual representation in miles:

In the constructor:

Binding bind = new Binding("Text", source, "PropertyName");

bind.Format += bind_Format;
bind.Parse += bind_Parse;

textBox.DataBindings.Add(bind);

...

void bind_Format(object sender, ConvertEventArgs e)
{
    int km = (int)e.Value;

    e.Value = ConvertKMToMiles(km).ToString();
}

void bind_Parse(object sender, ConvertEventArgs e)
{
    int miles = int.Parse((string)e.Value);

    e.Value = ConvertMilesToKM(miles);
}
like image 144
Adam Robinson Avatar answered Sep 28 '22 09:09

Adam Robinson