Mister 832
Mister 832

Reputation: 1221

Extend Custom Datatable to provide additional methods

I want to make it a little easier, to assign values of the DataRow Collection to Properties of some Objects.

I want to do something like this:

Tabelle t = new Tabelle(query, Id, 1200);

foreach (DataRow r in t.Rows)
{
    CustObject b = new CustObject();

    r.AssingValue(Columnname, b, PropertyName);
}

The Table looks like this:

internal class Tabelle : DataTable
{
    DataTable tabelle = new DataTable();

    internal Tabelle(string abfrage)
    {
        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter((SqlCommand)new Prozedur(abfrage));
            if (adapter.SelectCommand.Connection != null && adapter.SelectCommand.Connection.State == ConnectionState.Open)
            {
                adapter.Fill(this);
            }
        }
    }

    // How can I attach this method to the datarow Collection?
    public void AssingValue(string parametername, object target, string propertyName)
    {
        if (Row.Value != System.DBNull.Value) // how would I access the DataRow Value? 
        {
            var prop = target.GetType().GetProperty(propertyName);
            prop.SetValue(target, Convert.ToDateTime(Row.Value));
        }

    }

}

Upvotes: 1

Views: 53

Answers (2)

Wheels73
Wheels73

Reputation: 2890

if i understand you correctly, you can achieve this with an extention method on the datarow class itself

public static class DataRowExtensionMethods
{
    public static int ReturnIntForField(this DataRow data, string fieldName)
    {
        return data[fieldName] == DBNull.Value ? 0 : Convert.ToInt32(data[fieldName]);
    }

    public static DateTime ReturnDateTimeFromDataRowField(this DataRow data, string fieldName)
    {
        return Convert.ToDateTime(data[fieldName]);
    }
} \\etc... etc...

We can then re-write your datarow loop as per the below.

foreach (DataRow r in t.Rows)
{
    CustObject b = new CustObject();
    b.PropertyName = r.ReturnIntForField("ColumnName");         
    b.PropertyName1 = r.ReturnDateTimeFromDataRowField("ColumnName1");
}

Hope that helps

Upvotes: 1

Nino
Nino

Reputation: 7105

your Assign method should have input parameters such as rowIndex to find specific row in your table and columnName, to get/set row's column value.

You can try something like this:

public void AssingValue(string columnName, object target, string propertyName, int rowIndex)
{
    DataRow row = this.Rows[rowIndex];
    if (row[columnName] != System.DBNull.Value) // how would I access the DataRow Value? 
    {
        var prop = target.GetType().GetProperty(propertyName);
        prop.SetValue(target, Convert.ToDateTime(row[columnName]));
    }

}

Upvotes: 0

Related Questions