1. using

    System;

  2. using

    System.Collections.Generic;

  3. using

    System.ComponentModel;

  4. using

    System.Data;

  5. using

    System.Drawing;

  6. using

    System.Linq;

  7. using

    System.Text;

  8. using

    System.Windows.Forms;

  9. using

    System.Data.SqlClient;

  10. namespace

    AllSaveGrid
  11. {

  12. public

    partial

    class

    Form1 : Form
  13. {
  14. DataSet ds =

    new

    DataSet();

  15. public

    Form1()
  16. {
  17. InitializeComponent();
  18. GridControl_Bind();
  19. }

  20. public


    void

    GridControl_Bind()
  21. {
  22. SqlClass sc =

    new

    SqlClass();

  23. //DataSet ds = new DataSet();
  24. ds = sc.SelTable();

    //获取DataGridView的数据源
  25. dataGridView1.DataSource = ds.Tables[0];
  26. }

  27. private


    void

    button1_Click(

    object

    sender, EventArgs e)
  28. {
  29. SqlConnection con =

    new

    SqlConnection(

    "server='localhost';database='Work';user='sa';password='123'"

    );
  30. SqlCommand cmd =

    new

    SqlCommand();
  31. cmd = con.CreateCommand();
  32. cmd.CommandText =

    "select * from Table_gongzi"

    ;
  33. SqlDataAdapter da =

    new

    SqlDataAdapter(cmd);
  34. SqlCommandBuilder cb =

    new

    SqlCommandBuilder(da);

    //使用SqlCommandBuilder的话,首先要求你的表有主键

  35. //然后他会根据你提供的查询语句,生成插入,修改,删除语句

  36. //再根据DataTable对应的数据行状态来调用对应的语句执行数据库操作
  37. da.Update(ds.Tables[0]);
  38. dataGridView1.Update();
  39. }

  40. private


    void

    button2_Click(

    object

    sender, EventArgs e)
  41. {
  42. DataRowView drv = dataGridView1.SelectedRows[0].DataBoundItem

    as

    DataRowView;
  43. drv.Delete();
  44. SqlConnection con =

    new

    SqlConnection(

    "server='localhost';database='Work';user='sa';password='123'"

    );
  45. SqlCommand cmd =

    new

    SqlCommand(

    "select * from Table_gongzi"

    , con);

  46. //          SqlCommand cmd = new SqlCommand();

  47. //          cmd = con.CreateCommand();

  48. //          cmd.CommandText = "select * from Table_gongzi";
  49. SqlDataAdapter da =

    new

    SqlDataAdapter(cmd);
  50. SqlCommandBuilder cb =

    new

    SqlCommandBuilder(da);

    //必须new SqlCommandBuilder 否则da.Update报错
  51. da.Update(ds.Tables[0]);
  52. dataGridView1.Update();
  53. }
  54. }
  55. }



转载声明:


本文转自

http://blog.csdn.net/shanzhaikaifa/archive/2009/08/13/4443931.aspx