SqlDataAdapter的Update(DataTable);
http://msdn.microsoft.com/zh-cn/library/z1z2bkx2.aspx

解决方案 »

  1.   

    SqlDataAdapter更新方法adapter.Update(数据集, 数据集中数据表名),下面是通过DataGridView提交更新数据集到数据库的示例public DataSet DsCustomer;
    public BindingSource BsCustomer;
    private const string connstr = @"Data Source=(local);User Id=sa;Password=123456;Initial Catalog=Database";
    public static DataSet getDataSet(string connStr, string sql, string name)
    {
    SqlConnection conn = null;
    DataSet ds = null;
    try
    {
    conn = new SqlConnection(connStr);
    ds = new DataSet();
    conn.Open(); SqlDataAdapter cmd = new SqlDataAdapter(sql, conn);
    cmd.Fill(ds, name);
    }
    catch
    {
    }
    finally
    {
    if (conn != null)
    conn.Close();
    }
    return ds;
    }public void UpdateDB()
    {
    try {

    DsCustomer = new DataSet();
    DsCustomer = getDataSet(connstr, "select * from Customer", "Customer");

    SqlConnection conn = new SqlConnection(connstr);
    conn.Open(); SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customer", conn);

    SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adapter);

    adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
    adapter.InsertCommand = commandBuilder.GetInsertCommand();

    adapter.Fill(DsCustomer);

    BsCustomer = new BindingSource();
    BsCustomer.DataSource = DsCustomer.Tables["Customer"];
    System.Diagnostics.Debug.Print("DS1 Rows:" + DsCustomer.Tables[0].Rows.Count.ToString());
    dataGridView1.DataSource = BsCustomer;//这里把dataGridView1的DataSource指向BindingSource DataRowView drv = BsCustomer.AddNew() as DataRowView;//如果是添加新记录的话
    drv.BeginEdit();//开始修改
    drv["Name"] = "fish";//该行item属性为“fish”
    drv["type"] = "2";//该行item属性为“fish”
    drv.EndEdit();
    //结束BindigSource编辑
    BsCustomer.EndEdit();
    //获取修改过的记录来只更新有改变的数据
    //DsCustomer.GetChanges();
    //System.Diagnostics.Debug.Print("DS1 Rows:" + DsCustomer.Tables[0].Rows.Count.ToString());
    //System.Diagnostics.Debug.Print("Changed: " + DsCustomer.HasChanges().ToString()); adapter.Update(DsCustomer, "Customer");
    //真正更新到数据库
    //DsCustomer.AcceptChanges();
    } catch (Exception) {
    throw;
    }
    }