【问题标题】:Why is a DataRow recognized in one part of a method but not another (how can I dynamically add DataRows)?为什么在方法的一部分中识别出 DataRow 而在另一部分中却不能识别(如何动态添加 DataRows)?
【发布时间】:2012-08-18 09:26:10
【问题描述】:

使用此代码:

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;

...我使用第 1 行(第 2a 和 2b 行注释掉)或使用第 2a 和 2b 行(第 1 行注释掉)得到这个编译时错误:

'System.Data.DataRow.DataRow(System.Data.DataRowBuilder)' 由于其保护级别而无法访问

这让我感到困惑,因为 for 循环中的 DataRow 是可以容忍的。如何将这些 DataRows 添加到我的 OracleDataTable?

【问题讨论】:

    标签: c# winforms oracle dynamic dotconnect


    【解决方案1】:

    DataRow的构造函数标记为protected internal,因此不能直接构造。

    DataTable 获取新行的正确代码是

    DataRow dr = dt.NewRow();
    

    【讨论】:

      【解决方案2】:

      我不熟悉OracleDataTable,但我认为它继承自普通的DataTable

      您不能直接创建DataRow,因为构造函数是protected。相反,您必须使用工厂方法之一,例如 DataTable.Rows.AddDataTable.NewRow。这可确保在新的 DataRow 上应用正确的架构,因为它是根据其 DataTable 确定的。

      所以这应该有效:

      while (iRows > 0)
      {
          DataRow dr = outputDt.NewRow();
          // fill the fields of the row ...
          // add it to the DataTable:
          outputDt.Rows.Add(dr);
          iRows -= 1;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-02
        • 1970-01-01
        相关资源
        最近更新 更多