Dynamically getting / setting an object property in C # 2005

I have inherited a code base, and I am writing a small tool to update a database. The code uses a data access layer such as SubSonic (but it is homegrown). There are many object properties, such as id, templateFROM, and templateTO, but there are 50 of them.

On the screen, I can’t display all 50 properties in my own text field for entering data, so I have a list of all possible properties and one text field for editing. When they select a property from the list, I populate the text box with the value that the property corresponds to. Then I need to update the property after editing is complete.

I am currently using two huge case statements. It seems silly to me. Is there a way to dynamically tell C # which property I want to set or get? Maybe like:

entObj."templateFROM" = _sVal; 

??

+4
source share
6 answers

You need to use System.Reflection for this task.

 entObj.GetType().GetProperty("templateFROM").SetValue(entObj, _sVal, null); 

This will help you.

+8
source

What you want is called reflection .

+2
source

I think you are looking for Reflection. Here is a small snippet:

 Type t = entObj.GetType(); t.GetProperty("templateFROM").SetValue(entObj, "new value", null); 

For the most part, usability notes (and fewer answers to your question), you might want to explore PropertyGrid controls. This list / text box sounds as if it's pretty tiring to use.

+2
source
 PropertyInfo[] properties = typeof(YourClass).GetProperties(BindingFlags.Instance | BindingFlags.Public) 

you can bind it to a dropdown list and then:

 PropertyInfo property = typeof(YourClass).GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public) property.SetValue(class, textBox.Text, null); 
+1
source

In the corresponding note, you will hate this interface if they need to update several properties at once. Can you split properties into groups or pages that the user can move faster?

+1
source

This example is useful.

 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; } 
0
source

All Articles