Datagridview更新删除

本文介绍了一个使用C#实现的窗体应用程序中如何通过DataGridView控件进行数据选择,并实现从数据库表中删除所选记录的功能。具体实现了:1) 通过DataGridView选择待删除的数据行;2) 从数据库中删除这些数据行;3) 更新DataGridView以显示最新数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

删除的时候同时不仅在体现..还删除了对应表的数据

代码:

 public partial class Form1 : Form

    {

        public DataSet ds = new DataSet();

        public SqlDataAdapter sdr;

        string strSql = "select * from tb";

        public SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[1].ConnectionString.ToString());



        public Form1()

        {

            InitializeComponent();

        }

        private void Form1_Load(object sender, EventArgs e)

        {

            datasetresource();

        }
	//更新后保存按钮



        private void button1_Click(object sender, EventArgs e)

        {

            SqlCommandBuilder scb = new SqlCommandBuilder(sdr);

            sdr.Update(ds, "a");

            datasetresource();

        }
	//删除按钮




        private void button2_Click(object sender, EventArgs e)

        {

            int i = this.dataGridView1.SelectedRows.Count;

            string strID="";

            while (i > 0)

            {

                strID += this.dataGridView1.SelectedRows[i - 1].Cells[0].Value.ToString()+",";//取出ID主键

                this.dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i - 1].Index);//删除界面数据

                i--;

            }
	//根据主键删除对应表数据

            conn.Open();

            string subID=strID.Substring(0,strID.Length-1);

            MessageBox.Show(subID.ToString());

            SqlCommand comm = new SqlCommand("delete from tb where id in(" + subID.ToString() + ")", conn);

            comm.ExecuteNonQuery();

            conn.Close();

            datasetresource();

        }
	//datagridview数据源
        public void datasetresource()

        {

            conn.Open();

            sdr = new SqlDataAdapter(strSql, conn);

            ds.Clear();

            sdr.Fill(ds, "a");

            conn.Close();

            //this.dataGridView1.DataSource = null;

            this.dataGridView1.DataSource = ds.Tables[0];

        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值