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

B. Clay Shannon picture B. Clay Shannon · Aug 22, 2012 · Viewed 10.3k times · Source

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?

Answer

Steve Czetty picture Steve Czetty · Aug 22, 2012

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