2

I have a datatable with a bunch of fields, and it's filled data by tableadapter. Usually, records that need to be inserted are a little bit different (only id). I don't want user to retypes everything again so, is there a quick way to insert current record into database. Notice that all my insert, update and delete operations are based on my 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);
}
sovantha
  • 259
  • 3
  • 16

2 Answers2

2

Try this to copy row:

        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);
Stecya
  • 22,896
  • 10
  • 72
  • 102
  • What is GUid.NewGuid();? I've got a error message: Unable to cast object of type 'System.Guid'to type 'System.IConvertable'. Couldn't store in ID Column. Expected type is Int32 – sovantha Nov 29 '11 at 12:53
  • In my example Id column is type of Guid, As I see you have int there so change it to some int.See my update – Stecya Nov 29 '11 at 12:58
0

The accepted answer didn't work for me because the TableAdapter query returned more columns than a new row had, 33. My table has 32 columns. This is legacy code and database.

However, this article gave me the answer: This Row already belongs to another table error when trying to add rows?

Community
  • 1
  • 1
Rhyous
  • 6,510
  • 2
  • 44
  • 50