日期:2014-05-18  浏览次数:20946 次

form中gridview的数据更新到数据库问题
返回的dataset给了gridview1
 
 public DataSet sql_retrieve(string s_sql)
 {
DataSet ds = new DataSet();
SqlConnection sqlcon;
sqlcon = new SqlConnection("Data Source=qiyou;Initial Catalog=test;User ID=sa");
sqlcon.Open();
adapter = new System.Data.SqlClient.SqlDataAdapter();
adapter.SelectCommand = new System.Data.SqlClient.SqlCommand(s_sql, sqlcon);
adapter.Fill(ds);
return ds;
}
在gridview中更改数据后,要如何将更改的数据写回数据库呢?

------解决方案--------------------
我以前做過這樣的例子:
 一: 全局變量
public DataSet DS;
private SqlCommand cmd;
private SqlDataAdapter adapter;
private SqlCommandBuilder builder;
  

二: 獲取數據
private void BindTest()
{
try
{
cmd = new SqlCommand("select * from Test", con);

DS = new DataSet();

adapter = new SqlDataAdapter(cmd);

builder = new SqlCommandBuilder(adapter);

con.Open();

adapter.Fill(DS, "Test");

bindingSource1.DataSource = DS;

bindingSource1.DataMember = "Test";

dataGridView1.DataSource = bindingSource1;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}

如果直接在datagridview裡編輯數據,在按鈕事件裡這樣寫就可以了
 adapter.Update(DS, "Test");