Search code examples
c#winformsuser-interfacedata-bindingbinding

How can I bind a List<T> to relevant text boxes on a form?


I have the following classes:

public class TemplateTestLine
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public string Hyperlink { get; set; }
        public int NumOfReadings { get; set; }
        public UnitOfMeasure UnitOfMeasure { get; set; } = new UnitOfMeasure();
        public MethodOfInput MethodOfInput { get; set; } = new MethodOfInput();  
        public bool Alarm { get; set; }
        public bool Signature { get; set; }
        public List<TemplateReading> Readings { get; set; } = new List<TemplateReading>();
    }

 public class TemplateReading
    {
        public int Id { get; set; }
        public int TestLineId { get; set; }
        public int ReadingTypeId { get; set; }
        public string Value { get; set; }
    }

In my database I have a number of reading types, which relate to the ReadingTypeId like so...

Id  Description
----------------
1   Distance Between Readings
2   Readings Target Min
3   Readings Target Max
4   Max Difference Between Readings
5   Tolerance Between Jumps
6   Straightness Max Difference Between Readings
7   Straightness Tolerance Between Jumps
8   Straightness Target Min
9   Straightness Target Max
10  Readings Tolerance Min
11  Readings Tolerance Max
12  Straightness Tolerance Min
13  Straightness Tolerance Max

To create or edit a TemplateTestLine I have a form with inputs(mainly text boxes) that I want to bind to the TemplateTestLine object that is passed to the form. So, 7 for each of the main properties (which are easy enough to bind using the 'Advanced DataBinding Editor'), plus 13 text boxes for the List<TemplateReading> like so...

current user interface

So my question is....

How can I bind the readings text boxes on the form so that when I pass a TemplateTestLine to the form, the List<TemplateReading> populate their relevant ReadingTypeId text boxes with the Value property?

Can it be done from the 'Advanced Binding Editor' or will I need to forget that and come up with a coded solution?

Thanks in advance.


Solution

  • To close this question, @Jimi's solution in the comments worked great:

    "It's simple enough to bind a Property of one of the objects in the list to the Text Property of the related TextBox"

    [TextBox].DataBindings.Add("Text", [TemplateTestLine Instance].Readings.Single(r => r.ReadingTypeId == 1), "Value", false, DataSourceUpdateMode.OnPropertyChanged);

    Thanks