Because Fill will not cause primary key and unique key information to be retrieved unless AddWithKey is specified, you must set the
MissingSchemaAction property to AddWithKey:
mySqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
mySqlDataAdapter.Fill(myDataSet, "Customers");
DataRow myDataRow;
myDataRow = myDataSet.Tables["Customers"].NewRow();
The DataTable must return a DataRow through the NewRow method. The method returns a DataRow object with the appropriate schema of the DataTable. The new DataRow is independent of the table until it is added to the RowsCollection.
myDataRow["CustomerId"] = "NewID";
myDataRow["ContactName"] = "New Name"; myDataRow["CompanyName"] = "New Company Name";
myDataSet.Tables["Customers"].Rows.Add(myDataRow);
To submit the data from the DataSet into the database, use the Update method on the SqlDataAdapter.
mySqlDataAdapter.Update(myDataSet, "Customers");
You can change data in a DataRow by accessing the DataRow. You can use the index of the row in the RowsCollection that is accessed through the Rows property:
myDataSet.Tables["Customers"].Rows[0]["ContactName"]="Peach";
You can also access a specific row by the primary key value:
DataRow myDataRow1 = myDataSet.Tables["Customers"].Rows.Find("ALFKI");
myDataRow1["ContactName"]="Peach";
In the preceding example, "ALFKI" is the value of the primary key "CustomerID" in the Customers table. When using the SqlDataAdapter, the key is established from the database. You can also set the key through the PrimaryKey property if you are not using the database.
Use the Delete method to remove the Row. Note that a logical deletion occurs in the DataSet, which only results in a hard deletion after the DataSet is updated to the database. Similarly, you can use RejectChanges on the DataSet, in which case the Row is restored.
myDataSet.Tables["Customers"].Rows[0].Delete();
The original and new values are maintained in the row. The RowChanging event allows you to access both original and new values to decide whether you want the edit to proceed. Because original and new values are maintained, you can establish scenarios such as optimistic locking and key changes.