扩展自定义数据表以提供其他方法

时间:2017-06-14 08:14:19

标签: c#

我想让它更容易一些,将DataRow集合的值分配给某些对象的属性。

我想做这样的事情:

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

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

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

表格如下:

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));
        }

    }

}

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你可以通过datarow类本身的扩展方法来实现这个目的

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...

然后我们可以按照下面的说法重新编写你的数据行循环。

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

希望有所帮助

答案 1 :(得分:0)

您的Assign方法应具有输入参数,例如rowIndex,以查找表格中的特定行和columnName,以获取/设置行的列值。

您可以尝试这样的事情:

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]));
    }

}