KamalSubodh
KamalSubodh

Reputation: 61

Convert a string to a property name

I have a class named AnchorLoadclass with properties like diameter, thickness. I have got a list of properties in a list. Now I want to iterate through a list and set value of properties as:

myanchor.(mylist[0]) = "200";

But it's not working. My code is as:

    private void Form1_Load(object sender, EventArgs e)
    {
        AnchorLoadclass myanchor = new AnchorLoadclass();
        var mylist = typeof(AnchorLoadclass).GetProperties().ToList();
        myanchor.GetType().GetProperty(((mylist[0].Name).ToString())) = "200";

        myanchor.thickness ="0.0";
        propertyGrid1.SelectedObject = myanchor;         
    }

Upvotes: 1

Views: 4631

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186843

As you forgot to mention in the question, the line

myanchor.GetType().GetProperty(((mylist[0].Name).ToString())) = "200";

doesn't compile (please avoid doesn't working). You have to do this:

 // 1. Get property itself:
 String name = "diameter"; // or mylist[0].Name or whatever name

 var propInfo = myanchor.GetType().GetProperty(name);

 // 2. Then assign the value
 propInfo.SetValue(myanchor, 200);

Often, it is a good practice to

  // Test, if property exists
  if (propInfo != null) ...

  // Test, if property can be written
  if (propInfo.CanWrite) ...

etc.

Upvotes: 3

Edin
Edin

Reputation: 1496

You should use PropertyInfo to set the property value (200) on the object (myanchor) as follows:

PropertyInfo propertyInfo = myanchor.GetType().GetProperty(((mylist[0].Name).ToString()));
propertyInfo.SetValue(myanchor, 200);

Upvotes: 0

Related Questions