c#:datagridview显示数据了,怎么把它的变动更新到数据库?

2025-03-22 22:42:15
推荐回答(1个)
回答1:

代码写在类里面,要写完整了才能灵活应用,你不要每次操作都去打开一次数据库链接,那样会造成死锁。

        public DataSet ds = null;
        public SqlDataAdapter sda = null;
        public static SqlConnection conn = null;
        public void OpenLink()
        {
            conn = new SqlConnection();
            conn.ConnectionString = "Server=192.168.1.2;UID=sa;PWD=**112*;DataBase=454545";
            try
            {
                conn.Open();
            }
            catch
            {
               MessageBox.Show("连接数据库失败!");
            }
        }
     public void saveTable()         
     {
            if (ds != null)
            {
                sda.Update(ds.Tables[0]);
                MessageBox.Show("操作已成功!","保存数据",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }
        public void link(String sql)
        {
            if (conn != null)
            {
                ds = new DataSet();
                sda = new SqlDataAdapter();
                sda.SelectCommand = new SqlCommand(sql, conn);
                SqlCommandBuilder builder = new SqlCommandBuilder(sda);
                sda.Fill(ds);
            }
        }
        public void filldata(DataSet ds, BindingNavigator b, DataGridView d)
        {
            BindingSource bs = new BindingSource();
            bs.DataSource = ds.Tables[0];
            b.BindingSource = bs;
            d.DataSource = bs;
        }

在你整个项目启动的时候初始化数据就OpenLink(),filldata就是填充dataGridView绑定导航,link()直接填写SQL语句就好了,在link的基础上saveTable()