桦山涧

桦山涧
Asp.net ---->知识改变命运!
posts - 261, comments - 171, trackbacks - 6, articles - 3
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

公告

Winform实践SqlCommandBuilder

Posted on 2008-06-05 15:25 桦林 阅读(...) 评论(...) 编辑 收藏

    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();
            }
        }

    }