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

郁闷了两天的问题
我的datagirdview想绑定数据库中的一张表,点击更新按钮后更新到数据库中,
下面是我的代码,并没有抓到异常,而是直接弹出更新成功对话框,郁闷
 private void button1_Click(object sender, EventArgs e)
  {
  try
  {
  string source = "pcdb.mdb";
  string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source;
   
  OleDbConnection olecon = new OleDbConnection(conn);
  OleDbDataAdapter da = new OleDbDataAdapter("select * from jsgx", olecon);
   
  DataSet ds = new DataSet();
  da.Fill(ds);
  dataGridView1.DataSource = ds.Tables[0];
   
   
  OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
  //保存 
  da.Update(ds);
   
  }
  catch(System.Exception ex)
  {
  MessageBox.Show(ex.ToString()); 
  return; 
  }
  MessageBox.Show("更新成功!"); 
  }
哪位帮帮忙,我郁闷死了

------解决方案--------------------
C# code

public partial class Form1 : Form
    {
Form1数据成员#region Form1数据成员
        private DataTable DT = new DataTable();
        private SqlDataAdapter SDA = new SqlDataAdapter();
#endregion

Form1构造函数#region  Form1构造函数 
        public Form1()
        {
            InitializeComponent();
        }
#endregion

连接数据库显示数据#region  连接数据库显示数据
        private void Form1_Load(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection("server=127.0.0.1;database=pubs;uid=sa");
            SqlCommand SCD = new SqlCommand("select * from tables", conn);
            SDA.SelectCommand = SCD;
            SDA.Fill(DT);
            dataGridView1.DataSource = DT;
        }
#endregion

使用Update更新数据库#region  使用Update更新数据库
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                SqlCommandBuilder SCB = new SqlCommandBuilder(SDA);                
                SDA.Update(DT);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
            MessageBox.Show("更新成功!");
        }
#endregion