Following code gives a red squigly under "emp.(col.ColummnName)". Error is "identifier expected"
foreach (DataColumn col in dt.Columns)
{
emp.(col.ColumnName) = row[(col.ColumnName)];
}
emp is a custom class with property names which correspond to column names in dataTable dt.
I suspect that I have to construct the expression differently so that I can refer to a property of class emp with results of a method call (col.ColumnName).
Any ideas will be appreciated.
==========================
Final Answer with working function code;
public void rowToObject(ref DataRow dr, ref object myObj)
{
foreach (DataColumn dc in dr.Table.Columns)
{
string colName = dc.ColumnName;
object colValue = dr[colName];
if (object.ReferenceEquals(colValue, DBNull.Value))
{
colValue = null;
}
PropertyInfo pi = myObj.GetType().GetProperty(colName);
if (pi != null && colValue != null)
{
Type propType = null;
Type nullableType = Nullable.GetUnderlyingType(pi.PropertyType);
if (nullableType != null)
{
propType = nullableType;
}
else
{
propType = pi.PropertyType;
}
if (object.ReferenceEquals(propType, colValue.GetType()))
{
pi.SetValue(myObj, colValue, null);
}
}
}
}