Why is a DataRow recognized in one part of a method but not another (how can I dynamically add DataRows)?

StackOverflow https://stackoverflow.com/questions/12081875

Question

With this code:

OracleDataTable dt = PlatypusSchedData.GetAvailablePlatypi(); 
OracleDataTable outputDt = new OracleDataTable();

int iRows = 12;
while (iRows > 0)
{
    outputDt.Rows.Add(new DataRow()); // line 1
    //var dr = new DataRow();     // line 2a
    //outputDt.Rows.Add(dr);      // line 2b
    iRows -= 1;
}

for (int i = 0; i < dt.Rows.Count; i += 1) {
    DataRow dr = dt.Rows[i];
    int outputColumn = 0;
    if (i % 12 == 0 && i > 0) {
        outputColumn += 1; //2?
    }
    outputDt.Rows[i % 12][outputColumn] = dr[0];
    outputDt.Rows[i % 12][outputColumn + 1] = dr[1];
}
dataGridView1.DataSource = outputDt;

...I get this compile-time error using either line 1 (lines 2a and 2b commented out) or using lines 2a and 2b (with line 1 commented out):

'System.Data.DataRow.DataRow(System.Data.DataRowBuilder)' is inaccessible due to its protection level

This is baffling me because the DataRow in the for loop is tolerated. How can I add these DataRows to my OracleDataTable?

Was it helpful?

Solution

The constructor for DataRow is marked as protected internal, and as such, you cannot construct it directly.

The correct code to get a new row for a DataTable is

DataRow dr = dt.NewRow();

OTHER TIPS

I'm not familiar with OracleDataTable but i assume that it inherits from a normal DataTable.

You cannot create a DataRow directly because the constructor is protected. Instead you must use one of the factory methods like DataTable.Rows.Add or DataTable.NewRow. This ensures that the correct schema is applied on the new DataRow because it's determined from its DataTable.

So this should work:

while (iRows > 0)
{
    DataRow dr = outputDt.NewRow();
    // fill the fields of the row ...
    // add it to the DataTable:
    outputDt.Rows.Add(dr);
    iRows -= 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top