Zeus
Zeus

Reputation: 1590

Reflection to get and use class properties

I am trying to update a linked list from a datagridview using reflection so I don't have to write a line of code for each property.

The class:

public class clsUnderlying
{
    public int UnderlyingID { get; set; }
    public string Symbol { get; set; }
    public double RiskFreeRate { get; set; }
    public double DividendYield { get; set; }
    public DateTime? Expiry { get; set; }
}

One line of code per property works:

UdlyNode.Symbol = (string)GenericTable.Rows[IDX].Cells["Symbol"].Value;
UdlyNode.Expiry = (DateTime)GenericTable.Rows[IDX].Cells["Expiry"].Value;
etc.

But there are many classes and class properties, so I'd prefer to use a loop and reflection, but I'm not sure how, and my attempt below has errors.

PropertyInfo[] classProps = typeof(GlobalVars.clsUnderlying).GetProperties(); 
foreach (var Prop in classProps)
{
    Type T = GetType(Prop); // no overload for method GetType
    UdlyNode.Prop.Name = Convert.T(GenericTable.Rows[IDX].Cells[Prop.Name].Value); // error on "Prop.Name" and "T.("
}

Thanks for any suggestions or links to further my understanding.

Upvotes: 1

Views: 127

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Reflection-based loop needs to use a different syntax:

  • Property type is a property of PropertyInfo,
  • Convert has a ChangeType method that takes System.Type, and
  • Property assignment needs to be done by calling SetValue

Therefore, your loop would look like this:

foreach (var p in classProps) {
    p.SetValue(
        UdlyNode
    ,   Convert.ChangeType(
            GenericTable.Rows[IDX].Cells[p.Name].Value
        ,   p.PropertyType
        )
    );
}

Upvotes: 2

Mong Zhu
Mong Zhu

Reputation: 23732

I would suggest to use BindingSource. This way a changed value in the Grid will automatically be changed in your list:

BindingSource bs = new BindingSource();
bs.DataSource = yourList;

dataGridView1.DataSource = bs;

This would solve the case where you want to update values manually changed in the grid.

Upvotes: 1

Related Questions