c# sql update - InvalidOperationException
本文关键字:InvalidOperationException update sql | 更新日期: 2023-09-27 18:25:38
我正在处理一个需要数据库的项目
我在Youtube上找到了一个教程,它演示了如何使用SQLServer2005连接和编辑数据。
但当我尝试时,我收到了这个错误InvalidOperationException
这是整个编辑代码
con.Open();
DataTable dt = new DataTable();
//load all records from sample table
SqlDataAdapter da = new SqlDataAdapter("select * from sampleEdit where ID=" +
textBox1.Text + " ", con);
da.Fill(dt);
//start the editing of the selected record
dt.Rows[0].BeginEdit();
dt.Rows[0][1] = textBox2.Text;
//stop the editing
dt.Rows[0].EndEdit();
//declare the sql commandbuilder that allow saving of records
SqlCommandBuilder cb = new SqlCommandBuilder(da);
//update the database
da.Update(dt);
//close the connection
con.Close();
//call the method that display the record to the gridview
displayRecords();
错误显示在更新部分
应该是什么问题?
这是的完全异常错误
System.InvalidOperationException: Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
at System.Data.Common.DbDataAdapter.UpdatingRowStatusErrors(RowUpdatingEventArgs rowUpdatedEvent, DataRow dataRow)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataTable dataTable)
at DatabaseConnect3.Form1.btnEdit_Click(Object sender, EventArgs e)
您的源表无效,因为您很可能没有在表上定义主键。只要将ID列作为表的主键,代码就可以工作了。