【问题标题】:Quick way to insert the same record as copy using Tableadapter使用 Tableadapter 插入与副本相同的记录的快速方法
【发布时间】:2011-11-29 12:04:58
【问题描述】:

我有一个包含一堆字段的数据表,它是由 tableadapter 填充的数据。通常,需要插入的记录有点不同(只有 id)。我不希望用户再次重新输入所有内容,有没有一种快速的方法可以将当前记录插入数据库。请注意,我所有的插入、更新和删除操作都是基于我的 tableadapter。

//Get only one last record that has been added when the form load.
bookTableAdapter.FillByLastID(bookDataSet.dtBook);

private void btnNew_Click(object sender, EventArgs e)
{  
  bookBindingSource.AddNew();  
}

private void btnSave_Click(object sender, EventArgs e)
{
  this.Validate();
  bookBindingSource.EndEdit();
  bookTableAdapter.Update(bookDataSet.dtBook);
}

【问题讨论】:

  • 一些代码示例会很棒。因为不清楚您如何进行更新工作。你张贴整张桌子还是什么?
  • 我只是我的datadapater上的更新方法。我一次发布一条记录。

标签: c# ado.net tableadapter


【解决方案1】:

试试这个复制行:

        DataRow row = table.Rows[0]; // row you want to copy

        DataRow newRow = table.NewRow();
        newRow.ItemArray = row.ItemArray.ToArray();
        newRow["Id"] = 10;  // change Id

        table.Rows.Add(newRow);

【讨论】:

  • 什么是 GUId.NewGuid();?我收到一条错误消息:无法将“System.Guid”类型的对象转换为“System.IConvertable”类型。无法在 ID 列中存储 。预期类型是 Int32
  • 在我的示例中,Id 列是 Guid 类型,我看到你在那里有 int,所以将其更改为一些 int。查看我的更新
【解决方案2】:

接受的答案对我不起作用,因为 TableAdapter 查询返回的列多于新行的列数,33。我的表有 32 列。这是遗留代码和数据库。

不过,这篇文章给了我答案:This Row already belongs to another table error when trying to add rows?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多