Reputation: 520
How to get value and type of "strx" at runtime? Cant get value of cell (properties) at runtime when using generics (as result of under code is "null").
Example
public class Foo
{
public int x, y;
public string strx, stry;
}
public void GetCellValueByName<T>(GridView gridview, string name/)
{
T = (T)Activator.CreateInstance(typeof(T));
object row = gridview.GetRow(gridview.GetSelectedRows()[0]);
if (row != null && row is T)
{
columnType = (T)gridview.GetRow(gridview.GetSelectedRows()[0]);
PropertyInfo info = columnType.GetType().GetProperty(name);
if (info != null)
{ // Here I got always null
info.GetValue(columnType, null);
}
}
}
string valueOfStrx = GetCellValueByName<Foo>(grid, "strx");
Upvotes: 0
Views: 4744
Reputation: 22501
The problem is that in class Foo
, strx
is a field (member variable):
public string strx, stry;
In your method, you try to use GetProperty
, but this will not find the field:
PropertyInfo info = columnType.GetType().GetProperty(name);
So either change the member to a property
public string strx { get; set; }
public string stry { get; set; }
or use GetField
instead:
FieldInfo info = columnType.GetType().GetField(name);
// ...
info.GetValue(columnType); // Note that GetValue for a field does not take a second parameter
Upvotes: 1