如图,WPF DataGrid绑定DataTable,然后点保存,没有问题,但修改了数据后点保存就出现以上的问题了,找了很久,找不到原因,请帮一下!
绑定代码如下 string rPair = (sender as ComboBox).SelectedItem.ToString(); DataTable tablek = new DataTable();
string sqlc = string.Format("select * from CUsers where 段数='{0}'", rPair);
SQLDataAdapter.Fill(sqlc, tablek);
dataGrid1.ItemsSource = tablek.DefaultView;
更新代码如下: private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string sqlc =string.Format( "select * from CUsers where 段数='{0}'", Customer.Sites);
DataTable tabled = dataGrid1.ItemsSource;
SQLHelper.UpdateDataTable(sqlc, tabled);
MesgBox.Show("客户资料保存成功!", 1);
dataGrid1.ItemsSource = tabled.DefaultView;
}
调用更新的方法如下:public static DataTable UpdateDataTable(string SqlString, DataTable table)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlDataAdapter Adapter = new SqlDataAdapter();
Adapter.SelectCommand = new SqlCommand(SqlString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(Adapter);
Adapter.Update(table);
return table;
}
}
关键问题是添加新行,保存存没有问题,修改数据后保存就有问题了。
update from table set ..... where field_a=.... and field_b=..... and field_c=.... and field_d=...
这类的代码,也就是把所有列都用来作为查询。如果你的select查询出来的数据在这样的where条件上还不能唯一确定一行,也就是说存在两行数据在这样的条件上相同,那么肯定会报这个异常了。所以你在select语句上注意访问主键列或者唯一键列,这就能确保不会抛出这样的异常。