Reputation: 1590
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
Reputation: 726509
Reflection-based loop needs to use a different syntax:
PropertyInfo
,Convert
has a ChangeType
method that takes System.Type
, andSetValue
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
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