一旦用户进行了编辑,您似乎正在运行此代码,名称为“RowEditEnding”。
所以我认为问题在于您只是在编辑完成后才创建MySqlCommandBuilder。
您需要先创建MySqlCommandBuilder,然后进行编辑,然后获取更新/插入/删除命令。
例如类似于以下内容(对不起,在 VB 中,但你明白了要点):
Using NotesDS As New DataSet
Using NotesDA As New SqlDataAdapter With {.SelectCommand = New SqlCommand With {.Connection = SQLDBConnection, .CommandText = "SELECT * FROM Notes WHERE ID = " & ID}}
NotesDA.Fill(NotesDS, "Notes")
Using NotesDV As New DataView(NotesDS.Tables("Notes"))
Using NoteBuilder As New SqlCommandBuilder(NotesDA) With {.QuotePrefix = "[", .QuoteSuffix = "]"}
If NotesDV.Count = 1 Then
Dim NoteDRV As DataRowView = NotesDV(0)
NoteDRV.BeginEdit()
NoteDRV.Item("UserName") = UserName
NoteDRV.Item("Note") = Note
NoteDRV.Item("NoteDate") = NoteDate
NoteDRV.Item("CompanyCode") = CompanyCode
NoteDRV.EndEdit()
NotesDA.UpdateCommand = NoteBuilder.GetUpdateCommand
NotesDA.Update(NotesDS, "Notes")
End If
End Using
End Using
End Using
End Using
编辑
@Eugene,你的DataGrid 绑定到什么?大概您将DataView 设置为DataContext?
如果是这种情况,那么您将使用DataAdapter 来填充DataView,也许是页面加载?这是您初始化MySqlCommandBuilder 所需的DataAdapter。
尝试以下方法:
- 在您的页面顶部声明您
DataAdapter、DataSet 和DataView。
- 使用 dtGrid 的
BeginningEdit 处理程序在声明的 DataAdapter 上初始化 MySqlCommandBuilder
- 使用
RowEditEnding 运行DataAdapter.Update 命令
例如(据我所知,我使用的是 SQL,但 MySQL 的工作原理相同)
using System.Windows;
using System.Windows.Controls;
using System.Data;
using System.Data.SqlClient;
namespace testApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private SqlDataAdapter myDataAdapter;
private DataView myDataView;
private DataSet myDataSet;
private SqlCommandBuilder myBuilder;
private SqlConnection myConn = new SqlConnection("CONNECTIONSTRING");
private void Window_Loaded(object sender, RoutedEventArgs e)
{
myConn.Open();
myDataAdapter = new SqlDataAdapter {SelectCommand=new SqlCommand() {Connection=myConn, CommandText="SELECT MINumber, CompanyName FROM EIncCompanies WHERE CompanyName LIKE 'Test%'" } };
myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "EIncCompanies");
myDataView = new DataView(myDataSet.Tables["EIncCompanies"]);
dtGrid.DataContext = myDataView;
}
private void dtGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
myBuilder = new SqlCommandBuilder(myDataAdapter) { QuotePrefix="[", QuoteSuffix="]"};
DataRowView myDRV = (DataRowView)dtGrid.SelectedItem;
myDRV.BeginEdit();
}
private void dtGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
DataRowView myDRV = (DataRowView)dtGrid.SelectedItem;
myDRV.EndEdit();
myDataAdapter.UpdateCommand = myBuilder.GetUpdateCommand();
myDataAdapter.Update(myDataSet, "EIncCompanies");
}
}
}
我还在DataGrid中的绑定上设置了Mode=TwoWay, UpdateSourceTrigger=PropertyChanged。