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

datagridview更新数据不成功,哪里出问题了?
保存按钮代码:
 private void bt_save_Click(object sender, EventArgs e)
  {
  DataSet ds = new DataSet();
  SqlDataAdapter myAdapter=new SqlDataAdapter();
  ds=da.UpdateByDataSet(ds, "financetable");
  myAdapter.Update(ds, "financetable");
  dataGridView1.DataSource = ds.Tables["financetable"];
  }

UpdateByDataSet代码:
public DataSet UpdateByDataSet(DataSet ds,string tbname)
{  
  SqlCommand myCommand = new SqlCommand("select * from financetable", conn);  
  SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand );  
  SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter);
  myAdapter.InsertCommand = myCommandBuilder .GetInsertCommand();
  myAdapter.UpdateCommand = myCommandBuilder .GetUpdateCommand();
  myAdapter.DeleteCommand = myCommandBuilder .GetDeleteCommand();
  DataTable tb = null;
  tb = ds.Tables["financetable"];  
  try
{
  conn.Open();
  myAdapter.Fill(ds,"financetable");
  myAdapter.Update(ds, "financetable");  
  ds.GetChanges();
  ds.AcceptChanges();
  conn.Close();
 }
  catch(Exception err)
{
  err.ToString();
  conn.Close();  
}
  return ds;
}

哪里出问题了,貌似是datagridview数据改变后,dataTable值没有变化,要怎么修改?

------解决方案--------------------
//唉..LZ再复制我的代码试下,我以前是用这种方法没问题的,

private SqlDataAdapter dataAdapter;
private dataset ds=new dataset();

//点击查询按钮 查询数据并绑定datagridview 这里是一个点击查询的动作
public void bt_select_Click(object sender, EventArgs e)

SqlCommand myCommand = new SqlCommand("select * from financetable", conn);
myAdapter = new SqlDataAdapter(myCommand ); 
SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(myAdapter);
myAdapter.InsertCommand = myCommandBuilder .GetInsertCommand();
myAdapter.UpdateCommand = myCommandBuilder .GetUpdateCommand();
myAdapter.DeleteCommand = myCommandBuilder .GetDeleteCommand();
 ds.clear();
try
{
conn.Open();
myAdapter.Fill(ds,"table");
conn.Close();
dataGridView1.DataSource = ds.Tables["table"];
 }
catch(Exception err)
{
messagebox.show(err.ToString());
conn.Close();
}
}


//点击保存按钮
 private void bt_save_Click(object sender, EventArgs e)
{
  myAdapter.Update(ds, "table"); //这样就可以把数据库更新了...
}