Domanda

So I would like to extend the DataRow class by adding int to the class Obviously it is simple

public class DataRowWithInt : DataRow
{
    // Properties ///////////////////////////////////////////////////

    public int integer
    {
        get;
        set;
    }

    // Constructor //////////////////////////////////////////////////

    public DataRowWithInt(DataRowBuilder builder)
        : base(builder)
    {
    }
}

Now when you want to create new row you would have to call

DataTable intDataTable = new DataTable();
intDataTable.Columns.Add("temp");
DataRowWithInt row = intDataTable.NewRow();

But this gives you conversion error. How can I avoid this problem and get DataRowWithInt to intDataTable?

Thank you.

-- edit --

I am aware that DataTable class is not going to return me DataRowWithIn. I would like to create an inherited DataTable class but I do not know what to write on NewRow class

È stato utile?

Soluzione

If you can't simply use a DataTable with a single DataColumn of type int per @Tim's suggestion in the comments, then consider creating a typed DataTable. With a typed DataTable you can define column names and types as well as a number of other DataTable features and behaviors including how NewRow() works.

A demonstration doing this can be found in this article over at codeproject.com:
How to Manually Create a Typed DataTable

A nice thing about typed DataTable is you don't need to 'indirectly' reference columns by index or by column name, you can reference columns using property notation with Visual Studio's Intellisense helping you out. Here's an example:

var intDataTable = new YourTypedDataTable();
YourTypedDataRow row = intDataTable.NewRow();
row.Temp = 100;
intDataTable.Rows.Add(row);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top