Reflection extension method to bind DataRow values to object properties.


/ Published in: Visual Basic
Save to your folder(s)

This will populate object properties with values from a DataRow. The DataTable column names must match the property names and types of the target class.

Example:

DataTable dt = new DataTable();
dt.Columns.Add("TestString", typeof(string));
dt.Columns.Add("TestBool", typeof(bool));
dt.Columns.Add("TestInt", typeof(int));
dt.Columns.Add("TestDouble", typeof(double));
dt.Columns.Add("TestDecimal", typeof(decimal));
dt.Columns.Add("TestFloat", typeof(string));

DataRow dr = dt.NewRow();
dr["TestString"] = "Hello";
dr["TestBool"] = false;
dr["TestInt"] = DBNull.Value;
dr["TestDouble"] =4.56;
dr["TestDecimal"] = 7.89m;
dr["TestFloat"] = "3.14f";
dt.Rows.Add(dr);

TestClass tc = new TestClass();
dr.AssignObjectValue(tc);

class TestClass
{
public string TestString { get; set; }
public bool? TestBool { get; set; }
public int? TestInt { get; set; }
public double TestDouble { get; set; }
public decimal TestDecimal { get; set; }
public float TestFloat { get; set; }
}


Copy this code and paste it in your HTML
  1. <System.Runtime.CompilerServices.Extension()> _
  2. Public Sub AssignObjectValue(ByVal dr As DataRow, ByVal target As Object)
  3. For Each dc As DataColumn In dr.Table.Columns
  4. Dim colName As String = dc.ColumnName
  5. Dim colValue As Object = dr(colName)
  6.  
  7. If colValue Is DBNull.Value Then
  8. colValue = Nothing
  9. End If
  10.  
  11. Dim pi As PropertyInfo = target.GetType().GetProperty(colName)
  12. If pi IsNot Nothing AndAlso colValue IsNot Nothing Then
  13. Dim propType As Type = Nothing
  14. Dim nullableType As Type = Nullable.GetUnderlyingType(pi.PropertyType)
  15.  
  16. If nullableType IsNot Nothing Then
  17. propType = nullableType
  18. Else
  19. propType = pi.PropertyType
  20. End If
  21.  
  22. If propType Is colValue.GetType() Then
  23. pi.SetValue(target, colValue, Nothing)
  24. End If
  25. End If
  26. Next
  27. End Sub

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.