Reputation: 181
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
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:
Text
binding select Add Project Data Source... option Transport
typeThat will add transportBindingSource
to your application. Now you can select each TextBox and bind it to one of properties from your Transport
object:
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:
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;
Upvotes: 3