简体   繁体   中英

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 ?

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();
    }
}

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM