这个问题有点怪?

DENQH 2013-04-29 11:28:11

如图,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;
}
}

关键问题是添加新行,保存存没有问题,修改数据后保存就有问题了。
...全文
170 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
DENQH 2013-04-30
  • 打赏
  • 举报
回复
谢谢了,6楼的,结贴,这么简单的问题,不什么时候把这个删了
wanghui0380 2013-04-30
  • 打赏
  • 举报
回复
额,你只设置的自增,而非主键 往你的toolbar上看,有个钥匙形状的按钮看见木,看见了就点一下把。
u010429168 2013-04-29
  • 打赏
  • 举报
回复
因为你的表没有主键,所以无法自动生成SQL语句
DENQH 2013-04-29
  • 打赏
  • 举报
回复
数据库图
DENQH 2013-04-29
  • 打赏
  • 举报
回复
cuid就是自增列,是主键,这个选取后,再直接保存没有错,但只要改一下里面的数据,再保存就有问题目了。
  • 打赏
  • 举报
回复
包括主键列或者唯一键列,可以让程序执行也较快。 DbDataAdapter很可能要实现类似 update from table set ..... where field_a=.... and field_b=..... and field_c=.... and field_d=... 这类的代码,也就是把所有列都用来作为查询。如果你的select查询出来的数据在这样的where条件上还不能唯一确定一行,也就是说存在两行数据在这样的条件上相同,那么肯定会报这个异常了。 所以你在select语句上注意访问主键列或者唯一键列,这就能确保不会抛出这样的异常。
  • 打赏
  • 举报
回复
我从来不使用 DbDataAdapter。不过针对你贴的图,大致可以说一下。你的执行select功能command,必访问过主键或者唯一键,这样Adapter通过分析才能自动生成 update from ..... where .....这里的where表达式。如果无法分析出来哪个字段是唯一的,那么就会报这个错误。 通常,记得你给Adapter配置的Command命令中的select语句所返回的列总应该包括有主键列,这就行了。

111,098

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧