This is my first question here and please excuse me with this presenting style.
I have a MySQL table categories
with following columns:
Here is what I am trying to do;
categories
mysqldataadaptor
's update()
methodProblem is after I insert new row, my dataset's relevant row does not show the last inserted primary key (auto-generated one). But it shows the values.
This is the code where I add new row
var dr = ds.Tables["categories"].NewRow();
dr["c_code"] = "tst123";
dr["c_name"] = "123tdt";
ds.Tables["categories"].Rows.Add(dr);
This is the code where I update database
adp.Update(ds.Tables[tempTableName]);
and finally this is how I view the dataset SOON AFTER above line
dataGridView1.DataSource = ds.Tables["categories"];
PROBLEM:
In the gridview only c_code
and c_name
appear there.
How do I get the last inserted id
to dataset?
I would guess you have to do a new adp.Fill(ds) to get the ID. You only provide c_code and c_name. Hence, c_code and c_name are the only columns filled in the grid. adp.Update updates your database, it does not reload the entire dataset after an update for obvious reasons.
This is what worked for me: It is in VB but you can see what is going on.
mySQLdataAdapter.Update(myDataSet, table)
mySQLcommand.CommandText = "Select Last_Insert_ID();"
lastInsertID = dc.ExecuteScalar()
Running this code right after the mysql adapter update provides the last inserted ID for even though i am using a dataset.
You can use the RowUpdated event of the DataAdapter to query the last inserted ID and update the current row:
...
adp.RowUpdated += DataAdapter_RowUpdated; // Add this once to your DataAdapter
adp.Update(ds.Tables[tempTableName]);
...
private void DataAdapter_RowUpdated(object sender, MySqlRowUpdatedEventArgs e)
{
if (e.StatementType == StatementType.Insert)
{
string sql = "select last_insert_id()";
MySqlCommand cmd = new MySqlCommand(sql, e.Command.Connection);
e.Row["c_id"] = cmd.ExecuteScalar();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.