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中更改的数据都会更新到数据库中.