WinForms data binding - binding to objects in a list

I need help / guidance on WinForms data binding and I cannot get Google to help me with this.

Here is my script. Consider the following classes, similar to what I need:

public class Car { public string Name { get; set; } public List<Tire> Tires { get; set; } } public class Tire { public double Pressure { get; set; } } 

My instances of this object will be a Car class object with a list of four Tire objects. Please note: I will always have a known number of objects in the list.

Now I want to bind data to a form containing five text fields. One text field with the name of the car and one text field with each of the tires.

Any idea on how to make this work? The designer in VS does not seem to allow me to set this by assigning list indexes such as Tires [0] .Pressure.

My current solution is to bind to a "BindableCar", which will look like this:

 public class BindableCar { private Car _car; public BindableCar(Car car) { _car = car; } public string Name { get { return _car.Name; } set { _car.Name = value; } } public double Tire1Pressure { get { return _car.Tires[0].Pressure; } set { _car.Tires[0].Pressure = value; } } public double Tire2Pressure { get { return _car.Tires[1].Pressure; } set { _car.Tires[1].Pressure = value; } } public double Tire3Pressure { get { return _car.Tires[2].Pressure; } set { _car.Tires[2].Pressure = value; } } public double Tire4Pressure { get { return _car.Tires[3].Pressure; } set { _car.Tires[3].Pressure = value; } } } 

but it gets really ugly when my lists contain 20 instead of 4 objects, and for each of these objects I want to bind to 6 properties. This makes a huge "BindableObject"!

+7
c # data-binding winforms
source share
3 answers

While the WinForms designer cannot do this, have you tried setting the binding in code? I assume that there is no problem binding the text box to someCar.Tires [1] .Pressure.

+3
source share

It should be noted that you can bind controls to any type of object that implements IList , ICollection or IEnumerable interfaces or inherits from classes that implement these interfaces. Generic collections are also suitable for this kind of binding.

They are internally converted to an instance of IBindingList .

For more information, see the following links:

+17
source share

You should be able to bind to the list through code instead of the designer. Here's an example (just a few hours ago).

-one
source share

All Articles