Reputation: 19707
I've inherited a code base and I'm writing a little tool to update a database for it. The code uses a data access layer like SubSonic (but it is home-grown). There are many properties of an object, like "id", "templateFROM" and "templateTO", but there are 50 of them.
On screen, I can't display all 50 properties each in their own textbox for data entry, so I have a listbox of all the possible properties, and one textbox for editing. When they choose a property in the listbox, I fill the textbox with the value that property corresponds to. Then I need to update the property after they are done editing.
Right now I'm using 2 huge switch case statements. This seems stupid to me. Is there a way to dynamically tell C# what property I want to set or get? Maybe like:
entObj."templateFROM" = _sVal;
??
Upvotes: 4
Views: 2210
Reputation: 10981
This sample is helpful
public class aa
{
private string myVar;
public string value
{
get { return myVar; }
set { myVar = value; }
}
}
private void button1_Click(object sender, EventArgs e)
{
aa a1 = new aa();
System.Reflection.PropertyInfo pt = typeof(aa).GetProperty("value");
pt.SetValue(a1, "hi",null);
this.Text = a1.value;
}
Upvotes: 0
Reputation: 415600
On a related note, you're users will hate this interface if they need to update a lot of properties at once. Can you divide the properties into groups or pages that the user can move through more quickly?
Upvotes: 1
Reputation: 5924
I think what you're looking for is Reflection. Here's a little snippet:
Type t = entObj.GetType();
t.GetProperty("templateFROM").SetValue(entObj, "new value", null);
On more of a usability note (and less of an answering-your-question note), you might want to look into using a PropertyGrid control. That listbox/textbox sounds like it could be pretty tedious to use.
Upvotes: 2
Reputation: 144112
PropertyInfo[] properties = typeof(YourClass).GetProperties(BindingFlags.Instance | BindingFlags.Public)
you can bind this to your drop down list, and later on:
PropertyInfo property = typeof(YourClass).GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public)
property.SetValue(class, textBox.Text, null);
Upvotes: 1
Reputation: 14250
You need to use System.Reflection for that task.
entObj.GetType().GetProperty("templateFROM").SetValue(entObj, _sVal, null);
This should help you.
Upvotes: 8