C# 通过DataGridview的直接更新MSSQL

第一步 将MSSQL数据库数据显示到DataGridview中

/**首先连接数据库,再将数据库中数据存放在DataSet(或者DataTabel)中 因为二者用法相同,这里只介绍DataSet用法。
然后将dataGridView中的数据和存在DataSet中的数据进行绑定**/

public void showDataGridview(fileName)
{
   
   //fileName 为 库中表名
DataSet Ds = new DataSet();   
//连接数据库
SqlConnection coon = new SqlConnection();
//DataSource="IP地址/数据库服务器名称"
//database="数据库名称"
coon.ConnectionString="DataSource=MS-20160711YGWJ;database=Student;uid=sa;pwd=123456";
coon.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from " + fileName + "", coon);   
//将数据库中数据导入DataSet中   
da.Fill(Ds);
//dataGridView数据绑定
dataGridView1.DataSource = Ds.Tables[0];
coon.Close();
coon.Dispose();
}

第二步 在DataGridview中修改数据并更新到数据库

/ **编写dataGridView的CellValueChanged事件
动态MSSQL更新数据库**/

 public Frmtest()
{
 InitializeComponent();
 dataGridView1.CellValueChanged+=dataGridView1_CellValueChanged; 
}
void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
        //连接数据库
            SqlConnection coon = new SqlConnection();
            coon.ConnectionString="DataSource=MS-20160711YGWJ;database=Student;uid=sa;pwd=123456";
            coon.Open();
            //获取列标题
            string          strcolumn=dataGridView1.Columns[e.ColumnIndex].HeaderText;
            //获取焦点触发行的第一个值
            string strrow = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
            //获取当前点击的活动单元格的值
            string value = dataGridView1.CurrentCell.Value.ToString();
            string strcomm = "update " + fileName + "  set " + strcolumn + "='" + value + "'where stu_num = " + strrow;
      //格式:update 表名 set 列名 = value where id = strrow
            SqlCommand comm = new SqlCommand(strcomm, coon);
            comm.ExecuteNonQuery();
            coon.Close();
        }

猜你喜欢

转载自blog.csdn.net/x15037308498/article/details/70666909