在现有DataTable中创建新DataRow

时间:2014-07-09 08:07:36

标签: c#

电贺!我正在尝试创建DataRow并将其添加到现有的DataSet / DataTable。我遇到的问题是表似乎没有正确传播。我知道桌子存在但是它不会给我任何东西但是作为回报。有什么想法吗?

代码:

var TownDataSet = new DataSet("newDataSet");
var checkDataSet = new DataSet();
var checkDataTable = new DataTable();
var dataTableName = "someDataSet";
checkDataSet = TownDataSet.Clone();
checkDataTable = TownDataSet.Tables[dataTableName];
Console.WriteLine("STEP 4 " + checkDataSet.DataSetName);
Console.WriteLine("STEP 5 " + checkDataSet.Tables.Count);
Console.WriteLine("STEP 6 " + checkDataTable.TableName);

当我到达第6步时出错:

STEP 4 newDataSet
STEP 5 7
DataTableInsertTemp: System.NullReferenceException: Object reference not set to an instance of an object.

1 个答案:

答案 0 :(得分:0)

让我们分析一下:

var TownDataSet = new DataSet("newDataSet");
var checkDataSet = new DataSet();
var checkDataTable = new DataTable();
var dataTableName = "someDataSet";
checkDataSet = TownDataSet.Clone();
checkDataTable = TownDataSet.Tables[dataTableName];

其中:

  • checkDataSet是一个包含0个表的新DataSet;
  • checkDataTable是无数据集中包含的新DataTable

所以:

  • TownDataSet.Tables是一个空集合
  • TownDataSet.Tables [dataTableName]为空

请改为尝试:

   var dataTableName = "someDataSet";
   var TownDataSet = new DataSet("newDataSet");
   var checkDataSet = new DataSet();

   /* add a new DataTable to the DataSet.Tables collection */
   checkDataSet.Tables.Add(new DataTable(dataTableName));

    /* maybe you need to add some columns too */
    checkDataSet.Tables[dataTableName].Columns.Add(new DataColumn("columnA", typeof(int)));
    checkDataSet.Tables[dataTableName].Columns.Add(new DataColumn("columnB", typeof(string)));

    /* create and initialize a new DataRow for the Tables[dataTableName] table */
    var r = TownDataSet.Tables[dataTableName].NewRow();
    r["columnA"] = 1;
    r["columnB"] = "Some value";

    /* add it to the Tables[dataTableName].Rows collection */
    TownDataSet.Tables[dataTableName].Rows.Add(r);

修改

有几种方法可以将数据库映射到数据集。我可以建议你一些:

这是基本实施:

    DataSet ds = new DataSet();
    ds.Tables.Add(new DataTable("myTable"));
    da.FillSchema(ds.Tables["mytable"], SchemaType.Source);


    var dataTableName = "someDataSet";
    var TownDataSet = new DataSet("newDataSet");
    var checkDataSet = new DataSet();

    /* add a new DataTable to the DataSet.Tables collection */
    checkDataSet.Tables.Add(new DataTable(dataTableName));

    /*
     * Fit the sql statement and the connection string depending on your scenario
     * Set the *Command, *Connection and *DataAdapter actual provider
     */
    SqlCommand cmd = new SqlCommand("select * from myTable");
    SqlConnection conn = new SqlConnection("my connection string");
    SqlDataAdapter da = new SqlDataAdapter();

    cmd.Connection = conn;
    da.SelectCommand = cmd;

    /* that's it: the datatable is now mapped with the corresponding db table structure */
    da.FillSchema(checkDataSet.Tables[dataTableName], SchemaType.Source);