Here is the code snippet to convert a C# DataTable to an existing C# class. If the column name matches with C# field name, then the class object will be created and pushed out.
public static UserInfo GetUserInfoFromDataTable(DataTable userInfoTable)
{
if (userInfoTable.Rows.Count == 0) throw new Exception("No UserInfo records found.");
if (userInfoTable.Rows.Count > 1) throw new Exception("More than one UserInfo records found.");
DataRow oneRow = userInfoTable.Rows[0];
UserInfo togoUserInfo = new UserInfo();
var props = typeof(UserInfo).GetProperties();
foreach (var prop in props)
{
string propName = prop.Name;
if (oneRow.Table.Columns.Contains(propName))
{
object propNewValue = oneRow[propName];
prop.SetValue(togoUserInfo, propNewValue);
}
}
return togoUserInfo;
}
Happy Coding.
Cheers
Adam
No comments:
Post a Comment