如图,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;
            }
        }
关键问题是添加新行,保存存没有问题,修改数据后保存就有问题了。

解决方案 »

  1.   

    我从来不使用 DbDataAdapter。不过针对你贴的图,大致可以说一下。你的执行select功能command,必访问过主键或者唯一键,这样Adapter通过分析才能自动生成 update from ..... where .....这里的where表达式。如果无法分析出来哪个字段是唯一的,那么就会报这个错误。通常,记得你给Adapter配置的Command命令中的select语句所返回的列总应该包括有主键列,这就行了。
      

  2.   

    包括主键列或者唯一键列,可以让程序执行也较快。DbDataAdapter很可能要实现类似
        update from table set ..... where field_a=.... and field_b=..... and field_c=.... and field_d=...
    这类的代码,也就是把所有列都用来作为查询。如果你的select查询出来的数据在这样的where条件上还不能唯一确定一行,也就是说存在两行数据在这样的条件上相同,那么肯定会报这个异常了。所以你在select语句上注意访问主键列或者唯一键列,这就能确保不会抛出这样的异常。
      

  3.   

    cuid就是自增列,是主键,这个选取后,再直接保存没有错,但只要改一下里面的数据,再保存就有问题目了。
      

  4.   

    因为你的表没有主键,所以无法自动生成SQL语句
      

  5.   

    额,你只设置的自增,而非主键往你的toolbar上看,有个钥匙形状的按钮看见木,看见了就点一下把。