问题描述
我想问一下,在.NET中程序用分层法来,建了一个DataAccess层,数据处理都在里面,包括DataSet(DataSet是自己写的),现在想在界面层里编辑DataGridView控件中的数据,然后通过DataGridView提交到DataSet后再提交给数据库进行更新。//显示数据publicDataSetGetTable(){SqlCommandcmd=newSqlCommand();cmd.CommandText=@"SELECTID,ISBN,NameAS书名,AuthorAS作者,PressAS出版社,"+"PublishDateAS出版日期,PriceAS定价,PagesAS页数,BarcodeAS条码,CDAS光盘,"+"StorageAS库存量FROM[book1].[dbo].[Book]";cmd.Connection=cn;SqlDataAdaptersda=newSqlDataAdapter();sda.SelectCommand=cmd;DataSetds=newDataSet();sda.Fill(ds,"Book");cn.Close();returnds;}//更新数据集SqlConnectioncn=newSqlConnection(@"DataSource=B7RFYV0VR5W8IW6;InitialCatalog=book1;IntegratedSecurity=True");cmd.Connection=cn;this.dataGridView1.host();SqlDataAdaptersda=newSqlDataAdapter();//sda.=cmd;DataSetds=newDataSet();//sda.Fill(ds,"Book");SqlCommandBuilderbu=newSqlCommandBuilder(sda);sda.Update(ds,"Book");//this.dataGridView1.DataSource=ds.Tables["Book"];////this.dataGridView1.Columns["ID"].Visible=false;//sda.Update(ds,"Book");cn.Close();//db.InsertTable(insert);this.dd();}系统提示Update无法找到TableMapping['Book']或DataTable"Book"请问DataGridView编辑修改完后,提交到DataSet的正确写法是怎样?谢谢
解决方案
解决方案二:
SqlDataAdapteradapter;//声明一个全局的Adapter和DataSetDataSetds;privatevoidForm1_Load(objectsender,EventArgse){stringstrSql="select*fromTable1";SqlConnectioncon=newSqlConnection("server=DBServer;userid=sa;password=sa;database=dbTest");adapter=newSqlDataAdapter(strSql,con);SqlCommandBuildercb=newSqlCommandBuilder(adapter);//通过该语句生成相应的(insertinto/update/deleteSql)ds=newDataSet();adapter.Fill(ds);//填充DataSetdataGridView1.DataSource=ds.Tables[0];//绑定}privatevoidbutton1_Click(objectsender,EventArgse){//由于DataGridView已与DataSet绑定,对DataGridView的更改(添加/删除/更新)亦会自动改变DataSet//更新回数据库adapter.Update(ds);MessageBox.Show("数据更新成功!");}
解决方案三:
SqlDataAdaptersda;publicDataSetGetTable(){SqlConnectioncn=newSqlConnection(@"DataSource=B7RFYV0VR5W8IW6;InitialCatalog=book1;IntegratedSecurity=True");SqlCommandcmd=newSqlCommand();cmd.CommandText=@"SELECTID,ISBN,NameAS书名,AuthorAS作者,PressAS出版社,"+"PublishDateAS出版日期,PriceAS定价,PagesAS页数,BarcodeAS条码,CDAS光盘,"+"StorageAS库存量FROM[book1].[dbo].[Book]";cmd.Connection=cn;sda=newSqlDataAdapter();SqlCommandBuilderbu=newSqlCommandBuilder(sda);sda.SelectCommand=cmd;DataSetds=newDataSet();cn.Open();//一般连接的打开和关闭最好在一个方法里sda.Fill(ds,"Book");cn.Close();returnds;}publicvoidOtherMethod(){SqlConnectioncn=newSqlConnection(@"DataSource=B7RFYV0VR5W8IW6;InitialCatalog=book1;IntegratedSecurity=True");cn.Open();//this.dataGridView1.host();//要用前面的DataAdapter对象来更新现在的dssda.Update(ds,"Book");cn.Close();//this.dd();}