How to extend DataRow and DataTable in C # with additional properties and methods?

I would like to create a custom DataRow that will have, for example, the name IsCheapest.

public class RateDataRow : DataRow
{
    protected internal RateDataRow(DataRowBuilder builder) : base(builder)
    {
    }

    public bool IsCheapest { get; set ;}
}

And I want to have a new DataTable that only contains *** RateDataRow *** s, so .NewDataRow () returns an instance of RateDataRow as a new row.

What should be the implementation in a class that extends a DataTable?

Thank,

+5
source share
3 answers

It is not clear from your question whether you are familiar with typed datasets. This is basically what you are asking for.

XSD ( XSD Db). WinForms " " .

, , ..

.

0

, , . , . :

class Program
{
    static void Main(string[] args)
    {
        MyDataTable t1 = new MyDataTable();

        t1.Columns.Add(new DataColumn("Name", typeof(string)));
        t1.Columns.Add(new DataColumn("DateOfBirth", typeof(DateTime)));

        MyDataRow r1 = t1.NewRow() as MyDataRow;
        r1["Name"] = "Bob";
        r1["DateOfBirth"] = new DateTime(1970, 5, 12);
        t1.Rows.Add(r1);
    }
}

[Serializable]
public class MyDataTable : DataTable
{
    public MyDataTable()
        : base()
    {
    }

    public MyDataTable(string tableName)
        : base(tableName)
    {
    }

    public MyDataTable(string tableName, string tableNamespace)
        : base(tableName, tableNamespace)
    {
    }

    /// <summary>
    /// Needs using System.Runtime.Serialization;
    /// </summary>
    public MyDataTable(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }

    protected override Type GetRowType()
    {
        return typeof(MyDataRow);
    }

    protected override DataRow NewRowFromBuilder(DataRowBuilder builder)
    {
        return new MyDataRow(builder);
    }
}

[Serializable]
public class MyDataRow : DataRow
{
    public bool MyPropertyThatIdicatesSomething { get; private set; }

    public MyDataRow()
        : base(null)
    {
    }

    public MyDataRow(DataRowBuilder builder)
        : base(builder)
    {
    }
}
+9

DataTable GetRowType, . :

class Program
{
    static void Main(string[] args)
    {
        MyDataTable t = new MyDataTable();
        t.Rows.Add(t.NewRow()); // <-- Exception here, wrong type (base doesn't count).
    }
}

public class MyDataTable : DataTable
{
    public MyDataTable()
        : base()
    { }

    protected override Type GetRowType()
    {
        return typeof(MyDataRow);
    }
}

public class MyDataRow : DataRow
{
    public MyDataRow()
        : base(null)
    { }
}
+3

All Articles