Return to Snippet

Revision: 27808
at June 24, 2010 05:04 by s0lidmetal


Initial Code
<System.Runtime.CompilerServices.Extension()> _
        Public Sub AssignObjectValue(ByVal dr As DataRow, ByVal target As Object)
            For Each dc As DataColumn In dr.Table.Columns
                Dim colName As String = dc.ColumnName
                Dim colValue As Object = dr(colName)

                If colValue Is DBNull.Value Then
                    colValue = Nothing
                End If

                Dim pi As PropertyInfo = target.GetType().GetProperty(colName)
                If pi IsNot Nothing AndAlso colValue IsNot Nothing Then
                    Dim propType As Type = Nothing
                    Dim nullableType As Type = Nullable.GetUnderlyingType(pi.PropertyType)

                    If nullableType IsNot Nothing Then
                        propType = nullableType
                    Else
                        propType = pi.PropertyType
                    End If

                    If propType Is colValue.GetType() Then
                        pi.SetValue(target, colValue, Nothing)
                    End If
                End If
            Next
        End Sub

Initial URL


Initial Description
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; }
    }

Initial Title
Reflection extension method to bind DataRow values to object properties.

Initial Tags


Initial Language
Visual Basic