Kardo
Kardo

Reputation: 1708

ASP.NET, C#, How to dynamically identify the properties or method of a user control and add value to them?

In want to add dynamically the properties or methods of a user control from the code behind like this:

foreach (DataRow drModuleSettings in dsModuleSettings.Tables[0].Rows)
{
    if (!string.IsNullOrEmpty(dsModuleSettings.Tables[0].Rows[0]["SettingValue"].ToString()))
        userControl.Title = dsModuleSettings.Tables[0].Rows[0]["SettingValue"].ToString();
}

The "userControl.Title" is a sample, in fact it should be replaced by such a code:

        userControl.drModuleSettings["SettingName"] = dsModuleSettings.Tables[0].Rows[0]["SettingValue"].ToString();

The problem is I don't know how to do this.

Please someone help me.

Thanks!

Upvotes: 0

Views: 470

Answers (2)

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

You could use dynamic properties. Which would mean that, userControl.drModuleSettings will be of type dynamic.

You can then assign it a value at runtime like

userControl.drModuleSettings = new {SomeProperty = "foo", AnotherProperty = "bar"};

More about dynamic keyword and DynamicObject here and here.

Note - Requires C# 4.0 or above.

Upvotes: 0

rhughes
rhughes

Reputation: 9583

You will need to use Reflection.

Have a look at the following code and references:

See here: Set object property using reflection

Also, here: http://www.dotnetspider.com/resources/19232-Set-Property-value-dynamically-using-Reflection.aspx:

This code is from the above reference:

// will load the assembly
Assembly myAssembly = Assembly.LoadFile(Environment.CurrentDirectory + "\\MyClassLibrary.dll");

// get the class. Always give fully qualified name.
Type ReflectionObject = myAssembly.GetType("MyClassLibrary.ReflectionClass");

// create an instance of the class
object classObject = Activator.CreateInstance(ReflectionObject);

// set the property of Age to 10. last parameter null is for index. If you want to send any value for collection type
// then you can specify the index here. Here we are not using the collection. So we pass it as null
ReflectionObject.GetProperty("Age").SetValue(classObject, 10,null);

// get the value from the property Age which we set it in our previous example
object age = ReflectionObject.GetProperty("Age").GetValue(classObject,null);

// write the age.
Console.WriteLine(age.ToString());

Upvotes: 1

Related Questions