Questions
20.2.8.1: How do I obtain the value of an auto-incremented column?
Questions and Answers
20.2.8.1: How do I obtain the value of an auto-incremented column?
When using the commandBuilder you should
make sure that you set the
ReturnGeneratedIdentifiers property to
true.
Then, you can use an active view on a table to access the updated ID. For example:
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
da = new MySql.Data.MySqlClient.MySqlDataAdapter();
cmdBuilder = new MySql.Data.MySqlClient.MySqlCommandBuilder();
SystemDataDataSet = new System.Data.DataSet();
SystemDataDataView = new System.Data.DataView();
...
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM contacts";
da.SelectCommand = cmd;
da.Fill(SystemDataDataSet, "contacts");
cmdBuilder.DataAdapter = da;
cmdBuilder.ReturnGeneratedIdentifiers = true;
cmdBuilder.DataAdapter.SelectCommand.CommandText = "SELECT * FROM contacts";
cmdBuilder.RefreshSchema();
SystemDataDataView = SystemDataDataSet.Tables["contacts"].DefaultView;
SystemDataDataRow = SystemDataDataView.Table.NewRow();
SystemDataDataRow["status"] = 1;
SystemDataDataView.Table.Rows.Add(SystemDataDataRow);
da.Update(SystemDataDataSet, "contacts");
System.Console.WriteLine("ID after update: " + SystemDataDataRow["id"]);
The SystemDataDataRow object in this instance
provides the interface to the updated auto-increment value in
the id column.

User Comments
Add your own comment.