C#中,datagridview与sql数据源绑定后,通过控件更改数据如何自动回写更新到数据源

以前一直在绕弯路,其实用c#自己的datagridview的数据绑定向导有便利的特征,就是能够简单的显示数据库中的某个表,但是问题是,对datagridview的更改无法通过简单的方法回写到数据库中。

所以我已开始尝试的是在dataGridView1_CellEndEdit事件中加入sqlcommandbuilder的方法,进行dataadapter的update();

通过实际使用,始终无法激发此更新动作,看到csdn上也有朋友发现这样的问题,我后来想了个折中的 办法,就是加了个button控件,在空间的click事件中进行处理,但是不甘心呀。

最后在偶然的情况下发现了cellvalidated事件,于是代码放入:

private void dataGridVies1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            SqlCommandBuilder cb = new SqlCommandBuilder(sda);
            sda.Update(ds);
         }


这样,datagridview自动显示了数据源的数据,通过鼠标点击datagridview中的cell,进行更改、新增、删除行等动作都能自动更新到数据源了。休息一下;

附上源代码,希望对有相同问题的朋友有帮助:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Data.OleDb;
using System.Runtime.InteropServices;
namespace xlstosql1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
           
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            con.ConnectionString = connectionstr;
            
            sda = new SqlDataAdapter("select * from table_user", con);//定义dataadapter
            sda.Fill(ds );
            dataGridView1.DataSource = ds.Tables[0];//完成数据绑定,datagridview可以显示数据源了
            
        }
        string connectionstr = "integrated security=SSPI;Initial Catalog=****;Data Source=localhost;";//初始化连接字符串

        SqlConnection con = new SqlConnection();//
        SqlDataAdapter sda = new SqlDataAdapter();//

        DataSet ds = new DataSet();
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //此处不能放sda的update语句,
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
           
        }

        private void dataGridVies1_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            SqlCommandBuilder cb = new SqlCommandBuilder(sda);//此命令自动生成相关新增、删除、更新command
            sda.Update(ds);//更新数据源
         }

      
    }
}


 

猜你喜欢

转载自blog.csdn.net/chengriyue/article/details/8242199
今日推荐