public partial class Form1 : Form
{
//声明一个公共的dt
DataTable dt=null;
string strconn = string.Empty;
//声明一个公共的sql文本变量,查询和更新都通过这个来联通数据库
string sqltext = string.Empty;
public Form1()
{
InitializeComponent();
//初始化变量
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
strconn = "server=.;uid=huashanlin;pwd=123;database=TestDB";
sqltext = "select * from T_Order";
//加载数据
GetDate();
}
private void GetDate()
{
using (SqlConnection conn = new SqlConnection(strconn))
{
SqlDataAdapter sda = new SqlDataAdapter("select * from T_User", conn);
//这里名为dt的Datatable必须是公共的
dt = new DataTable();
sda.Fill(dt);
//绑定datagridview
dataGridView1.DataSource = dt;
//绑定文本框
tB1.DataBindings.Clear();
tB1.DataBindings.Add("text", dt, "UserID");
tB2.DataBindings.Clear();
tB2.DataBindings.Add("text", dt, "UserName");
}
}
private void btnAlter_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(strconn))
{
SqlDataAdapter sda = new SqlDataAdapter("select * from T_User", conn);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
sda.Update(dt);
MessageBox.Show("更新成功");
GetDate();
}
}
}