当前位置:编程学习 > C#/ASP.NET >>

在C#中使用控件DataGridView直接增删改数据库表的内容

能不能不用按钮,在_CellBeginEdit和_CellEndEdit直接实现增删改?求代码,详细最好啊, 

--------------------编程问答--------------------

        private SqlDataAdapter sda;
        private void Form3_Load(object sender, EventArgs e)
        {
            string connString = "server=.;database=test;uid=sa;pwd=Cdyouxi.kgen-1";
            string selectTxt = "select * from a";
            this.dataGridView1.DataSource = GetData(connString, selectTxt);
        }

        private DataTable GetData(string connString, string selectTxt)
        {
            SqlConnection conn = new SqlConnection(connString);
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = selectTxt;
            sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            SqlCommandBuilder scb = new SqlCommandBuilder(sda);
            return dt;
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            this.sda.Update((DataTable)this.dataGridView1.DataSource);
        }
--------------------编程问答--------------------
引用 1 楼 haukwong 的回复:
C# code1234567891011121314151617181920212223242526        private SqlDataAdapter sda;        private void Form3_Load(object sender, EventArgs e)        {            string connString = "s……
最后一行没法保存,而且修改好了直接关闭窗体再打开看没效果啊 --------------------编程问答-------------------- 除 --------------------编程问答--------------------  this.dataGridView1.DataSource = GetData(connString, selectTxt);
 this.dataGridView1.databind();//少了重新绑定。、 --------------------编程问答--------------------
引用 4 楼 kongwei521 的回复:
this.dataGridView1.DataSource = GetData(connString, selectTxt);
 this.dataGridView1.databind();//少了重新绑定。、
 
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,