I am trying to reuse some code from a project that works with DataRow instead of object. In my new project I have the model created and I work all with objects but Im trying to bring that piece of code since its very large. So the question is how can I get a DataRow from an object.
class Person
{
public Int64 Id { get; set; }
public string Name { get; set; }
}
Person p1 = new Person();
p1.Id = 1;
p1.Name = "John";
// How to get a DataRow from this p1 object
drPerson["Id"] == 1
drPerson["Name"] == John
I am looking for a way to get done it automatically if that is possible
Thanks!
CodePudding user response:
So finally thanks to the comments I got this code that works but it might be better
public static DataRow ToDataRow(object from) {
DataTable dt = new DataTable();
foreach(PropertyInfo property in from.GetType().GetProperties()) {
DataColumn column = new DataColumn();
column.ColumnName = property.Name;
column.DataType = property.PropertyType;
dt.Columns.Add(column);
}
DataRow dr = dt.NewRow();
foreach(PropertyInfo property in from.GetType().GetProperties()) {
dr[property.Name] = property.GetValue(from);
}
return dr;
}
With these code I can a DataRow with the name of the columns as the object atributes and also the values of it.
-- Edit
Usually DataRow objects don't just hang out by themselves. They will belong to a DataTable. This method is creating a throwaway DataTable just to make a row. - siride
That is right so I've changed it to this
public static DataRow ToDataRow(object from, DataTable dt) {
DataRow dr = dt.NewRow();
foreach(PropertyInfo property in from.GetType().GetProperties()) {
dr[property.Name] = property.GetValue(from);
}
return dr;
}
public static DataTable GetDataTable(object from) {
DataTable dt = new DataTable();
foreach(PropertyInfo property in from.GetType().GetProperties()) {
DataColumn column = new DataColumn();
column.ColumnName = property.Name;
column.DataType = property.PropertyType;
dt.Columns.Add(column);
}
return dt;
}
With this change I can retrieve the DataTable before getting the DataRow and use both