在C#使用SqlDataAdapter的Update更新数据

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Configuration;
using System.Data.SqlClient;

namespace Sqltest
{
    public partial class Form1 : Form
    {
        string sqlconnection = ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
        SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter sda;
        SqlCommandBuilder scb;
        DataSet ds = new DataSet();
        public Form1()
        {
            InitializeComponent();
            BindData();
        }

        private void BindData()
        {
            con = new SqlConnection(sqlconnection);
            cmd = new SqlCommand();
            sda = new SqlDataAdapter();
            cmd.Connection = con;
            cmd.CommandText = "select * from T_Teacher";
            sda.SelectCommand = cmd;
            //该对象负责生成用于更新数据库的SQL语句,不必自己创建这些语句
            scb = new SqlCommandBuilder(sda);

            sda.Fill(ds, "DT");
            dataGridView_data.DataSource = ds.Tables[0];
        }

        private void button_update_Click(object sender, EventArgs e)
        {
            //直接改了dataGridView中的数据
            DataTable dt = (DataTable)dataGridView_data.DataSource;
            //更新数据(UpDate方法自动遍历DataTable中的行,以找出需要对数据库作出变动)
            //Rows集合中每个DataRow对象都具有属性RowState,
            //可以跟踪此行是否已删除、添加、修改,还是未作变动。
            //所作的任何变化都会反映到数据库中。
            sda.Update(dt);
            dataGridView_data.DataSource = dt;
        }
    }
}

点击更新后dataGridView中更改的数据都会更新到数据库中.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值