Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple DataBindings to Winforms label

I am displaying different values in a Label control from a BindingSource that is bound to a DataGridView depending on which row is selected.

Right now, the label has a databinding that looks as follows:

this.label9.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.bev_BindingSource, "countryRegion", true));

which successfully displays the value of the countryRegion column.

Is is possible to set the databinding as a concatenated result from two columns, in this case countryRegion and country?

like image 303
Daniel B Avatar asked Dec 06 '13 21:12

Daniel B


2 Answers

You'll need to use a MultiBinding. Add the two Binding instances (one for countryRegion and one for country. Then you'll need to implement an IMultiValueConverter that will accept the values produced by the two binding objects and convert them into a single value.

The binding setup would look something like this:

var multiBinding = new MultiBinding();
multiBinding.Bindings.Add(new Binding("Text", this.bev_BindingSource, "countryRegion", true));
multiBinding.Bindings.Add(new Binding("Text", this.bev_BindingSource, "country", true));
multiBinding.Converter = new MyMultiValueConverter();

this.label9.DataBindings.Add(multiBinding);

And the converter implementation would look something like:

public class MyMultiValueConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // perform your conversion here and return the final value
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
like image 138
Michael Gunter Avatar answered Sep 28 '22 06:09

Michael Gunter


You could create a computed property and bind to it. For example, create a Location property that returns the value, and bind to it

public class MyData
{
    public string CountryRegion {get;set;}
    public string Country {get; set;}

    public string Location
    get()
    { 
      return CountryRegion+" " + Country;
    }
}
like image 20
Rick Hodder Avatar answered Sep 28 '22 07:09

Rick Hodder