Matt Dawdy
Matt Dawdy

Reputation: 19707

Dynamically getting/setting a property of an object in C# 2005

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

Answers (6)

ebattulga
ebattulga

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

Joel Coehoorn
Joel Coehoorn

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

Mike Powell
Mike Powell

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

Rex M
Rex M

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

Thomas
Thomas

Reputation: 181705

What you want is called reflection.

Upvotes: 2

okutane
okutane

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

Related Questions