net_lover,专家,您好! 请问DataGridView编辑修改完后,提交到DataSet的正确写法是怎样?
我想问一下,在.NET中程序用分层法来,建了一个DataAccess层,数据处理都在里面,包括DataSet(DataSet是自己写的),现在想在界面层里编辑DataGridView控件中的数据,然后通过DataGridView提交到DataSet后再提交给数据库进行更新。//显示数据
public DataSet GetTable()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = @ "SELECT ID, ISBN, Name AS 书名, Author AS 作者, Press AS 出版社,"+
" PublishDate AS 出版日期, Price AS 定价, Pages AS 页数, Barcode AS 条码, CD AS 光盘,"+
"Storage AS 库存量 FROM [book1].[dbo].[Book]";
cmd.Connection = cn;
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds,"Book");
cn.Close();
return ds;
}
//更新数据集
SqlConnection cn = new SqlConnection(@"Data Source=B7RFYV0VR5W8IW6;Initial Catalog=book1;Integrated Security=True");
cmd.Connection = cn;
this.dataGridView1.host();
SqlDataAdapter sda = new SqlDataAdapter();
//sda. = cmd;
DataSet ds = new DataSet();
//sda.Fill(ds, "Book");
SqlCommandBuilder bu = new SqlCommandBuilder(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的正确写法是怎样?
谢谢 --------------------编程问答--------------------
SqlDataAdapter adapter;//声明一个全局的Adapter和DataSet--------------------编程问答-------------------- SqlDataAdapter sda;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
string strSql = "select * from Table1";
SqlConnection con = new SqlConnection("server=DBServer;user id=sa;password=sa;database=dbTest");
adapter = new SqlDataAdapter(strSql, con);
SqlCommandBuilder cb = new SqlCommandBuilder(adapter);//通过该语句生成相应的(insert into/update/delete Sql)
ds = new DataSet();
adapter.Fill(ds);//填充DataSet
dataGridView1.DataSource = ds.Tables[0];//绑定
}
private void button1_Click(object sender, EventArgs e)
{
//由于DataGridView已与DataSet绑定,对DataGridView的更改(添加/删除/更新)亦会自动改变DataSet
//更新回数据库
adapter.Update(ds);
MessageBox.Show("数据更新成功!");
}
public DataSet GetTable()
{
SqlConnection cn = new SqlConnection(@"Data Source=B7RFYV0VR5W8IW6;Initial Catalog=book1;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = @"SELECT ID, ISBN, Name AS 书名, Author AS 作者, Press AS 出版社," + " PublishDate AS 出版日期, Price AS 定价, Pages AS 页数, Barcode AS 条码, CD AS 光盘,"+ "Storage AS 库存量 FROM [book1].[dbo].[Book]";
cmd.Connection = cn;
sda = new SqlDataAdapter();
SqlCommandBuilder bu = new SqlCommandBuilder(sda);
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
cn.Open();//一般连接的打开和关闭最好在一个方法里
sda.Fill(ds,"Book");
cn.Close();
return ds;
}
public void OtherMethod()
{
SqlConnection cn = new SqlConnection(@"Data Source=B7RFYV0VR5W8IW6;Initial Catalog=book1;Integrated Security=True");
cn.Open();
//this.dataGridView1.host();
//要用前面的DataAdapter对象来更新现在的ds
sda.Update(ds, "Book");
cn.Close();
//this.dd();
}
补充:.NET技术 , C#