datagridview 更新数据库

来源:互联网 发布:定量和定性数据 编辑:程序博客网 时间:2024/05/21 19:44
     public partial class Form1 : Form

       {

        #region Form1数据成员

        private DataTable DT = new DataTable();

        private SqlDataAdapter DA = new SqlDataAdapter();

        #endregion

        #region  Form1构造函数

        public Form1()

        {

            InitializeComponent();

        }

        #endregion

        #region  连接数据库显示数据

        private void Form1_Load(object sender, EventArgs e)

        {

            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=tt;Persist Security Info=True;User ID=sa;Password=sunlang0924");
            
            SqlCommand SCD = new SqlCommand("select * from tab", conn);

            DA.SelectCommand = SCD;

            DA.Fill(DT);

            dataGridView1.DataSource = DT;

        }

        #endregion

        #region  使用Update更新数据库

        private void button1_Click(object sender, EventArgs e)

        {

            try

            {

                SqlCommandBuilder SCB = new SqlCommandBuilder(DA);            

                DA.Update(DT);

            }

            catch (System.Exception ex)

            {

                MessageBox.Show(ex.ToString());

                return;

            }

            MessageBox.Show("更新成功!");

        }

#endregion
原创粉丝点击