检索/同步新DataGrid行的autoincrement id

时间:2012-02-21 18:21:08

标签: c# mysql wpf data-binding datagrid

我有一个MySql数据库,其中一些表绑定到datagrids。我已经为我的MySqlDataAdapter设置了自定义INSERT,UPDATE等功能,这些功能似乎正在运行。我遇到的问题是当我向db添加一个新行时,id列是自动增量的 - 所以我需要从db返回到我的数据集中。 This method讨论创建存储过程和一堆其他代码来执行此操作,但是没有办法只刷新/重新同步新添加的行吗?当然,没有重新加载整个表格。

这是我的约束力:

string sql = "SELECT visits.*, patients.Name FROM visits, patients WHERE visits.FK_Patient_UPI = patients.UPI";

using (MySqlConnection connection = new MySqlConnection(Properties.Resources.SQLConnString))
{
    // fill the table
    connection.Open();
    using (MySqlCommand cmdSel = new MySqlCommand(sql, connection))
    {
        mDataSetVisits = new DataSet();
        mAdapterVisits = new MySqlDataAdapter(cmdSel);
        mAdapterVisits.Fill(mDataSetVisits, "visits");
        LoadAdapterVisits(mAdapterVisits, connection); // this creates the INSERT, UPDATE, etc. commands
        dataGridVisits.DataContext = mDataSetVisits.Tables["visits"];
    }
    connection.Close();
}

以下是我添加新行的方式(使用表单作为输入):

DataRow row = mDataSetVisits.Tables[0].NewRow();
row["Date"] = DateTime.Now;
row["FollowUpDate"] = DateTime.Now.AddMonths(3);
Window_NewVisit newVisit = new Window_NewVisit(row, true);

newVisit.ShowDialog();

if (newVisit.DialogResult.HasValue && newVisit.DialogResult.Value)
{
    mDataSetVisits.Tables[0].Rows.Add(row);
    mAdapterVisits.Update(mDataSetVisits, "visits");

    // At this point, the DB has the new row, the DataSet/DataGrid has it as well, 
    // but the autoincrement id of my "visits" table in my datarow is still NULL.
}

0 个答案:

没有答案