【问题标题】:Appending DataRow to DataTable filled from DataAdapter, clears all records将 DataRow 附加到从 DataAdapter 填充的 DataTable 中,清除所有记录
【发布时间】:2012-08-01 03:57:24
【问题描述】:

我有一个DataGridView,它绑定了一个DataTable,由PostgreSQL 数据库和Npgsql .NET 数据提供程序库填充。

填充记录有效,但是当我只想将一条记录附加到已经存在的DataTable 时,以前的记录就会消失:

NpgsqlDataAdapter npDataAdapterSingle = new NpgsqlDataAdapter("SELECT * from \"Weight\" ORDER BY id DESC LIMIT 1", this.npConnection);
DataTable tmpTable = new DataTable("tmpTable");
npDataAdapterSingle.Fill(tmpTable);

DSWeight.WeightRow row = this.dSWeight.Weight.NewWeightRow();
row.ItemArray = tmpTable.Rows[0].ItemArray;
this.dSWeight.Weight.Rows.InsertAt(row, 0); //Prepend, but i also tried this.dsWeight.Weight.Rows.Add(row);

如果我选择所有记录,没有LIMIT'ing,那么它会按预期工作。但我想——如果我已经有了这些记录,为什么还要重新查询数据库?这就是为什么我想LIMIT

也许还有另一种解决方案,因为我手动将新记录添加到数据库并查询它们以将它们添加到数据表,而不是应该的方式:将新记录添加到数据表并将它们添加到数据库。我这样做是因为我希望数据库管理 id 和时间戳字段并让 datagridview 填充这些字段。

我错过了什么?

【问题讨论】:

    标签: c# sql database datagridview datatable


    【解决方案1】:

    我不确定 DSWeight.WeightRow 的数据类型和“this”对象的范围,因为我只能看到部分代码,而不是完整的方法。这可能对你有用。请试一试。

    NpgsqlDataAdapter npDataAdapterSingle = new NpgsqlDataAdapter("SELECT * from \"Weight\" ORDER BY id DESC LIMIT 1", this.npConnection);
    DataTable tmpTable = new DataTable("tmpTable");
    npDataAdapterSingle.Fill(tmpTable);
    
    row =  tmpTable.NewRow();
    
    foreach (DataColumn col in tmpTable.Columns)
       row[col.ColumnName] = tmpTable.Rows[0][col.ColumnName];
    
    tmpTable.Rows.Add(row, 0);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 1970-01-01
      相关资源
      最近更新 更多