FlipTop
FlipTop

Reputation: 181

Use variable to access class property

I have a data class (simplified)

public class Transport
{
    public int TransId;
    public string TType;
    public string Color;
    public string Size;
}

Transport t1 = new Transport();
populate(t1)

With which I am populating textbox controls on a windows form. My textboxes have the same names (TransId, TType, Color, Size). There are many more so what I am trying to do is use the name of the textbox to access the data. Something like....

foreach (TextBox tb in this.Controls.OfType<TextBox>())
{
    tb.Text = t1.(tb.Name);
}

Is this possible? Is it even a good idea or should I stick to TransId.Text = t1.TransId etc?

Upvotes: 1

Views: 87

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

I suggest you to assign properties values to controls manually (especially if you want only displaying of values) or use Data Binding to bind class properties to controls:

  • Select one of TextBoxes and go to (DataBindings) property
  • For Text binding select Add Project Data Source... option
  • Select Object data source type
  • Select your Transport type

That will add transportBindingSource to your application. Now you can select each TextBox and bind it to one of properties from your Transport object:

enter image description here

All you need now is add Transport instance to binding source:

private Transport transport;

public Form1()
{
    InitializeComponent();

    transport = new Transport { 
                   TransId = 42, 
                   Color = "White", 
                   Size = "Big"
                   // ...
                };

    transportBindingSource.Add(transport);
}

Result:

enter image description here

Nice benefit of binding is that it works both ways - when you'll edit value in TextBox, transport object property will be updated.


NOTE: Consider to use PropertyGrid if you just want to show values of all properties of object:

 propertyGrid.SelectedObject = transport;

enter image description here

Upvotes: 3

Related Questions