DataGridView 选择更改事件并从数据库中删除选定的行 [英] DataGridView selection changed event and deleting selected rows from database

查看:32
本文介绍了DataGridView 选择更改事件并从数据库中删除选定的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单上有一个单选按钮、一个网格视图和一个按钮.这是我的 datagridview selection_changed 代码示例:

I have a radiobutton, a gridview and a button on my form. Here is my datagridview selection_changed code sample:

private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
    if (rdb_Delete.Checked)
    {
        lbl_deleteMsg.Text = DataGridView1.SelectedRows.Count.ToString() 
                + " rows selected.";
    }
 }

我想从数据库中删除选定的行并在用户按下删除按钮时刷新 datagridview.我的数据库中有一个 Id 列,但我没有在 datagridview 上向用户显示它.

I want to delete selected rows from database and refresh the datagridview when user pushes the delete button. I have an Id column in my database but I don't show it to the user on datagridview.

那么通过 sql 查询如何从我的数据库中删除选定的行?这是我点击删除按钮的代码,但它似乎不起作用(因为选择更改事件):

So by sql query how can I delete the selected row from my database? Here is my delete button clicked code but it doesn't seems to work (because of selection changed event):

private void btn_Delete_Click(object sender, EventArgs e) 
{       
    if (rdb_Delete.Checked)
    {
        int count = DataGridView1.SelectedRows.Count;
        int length = DataGridView1.RowCount;
        if (!count.Equals(0))
        {
            if (confirm())
            {
                for (int i = 0; i < length; i++)
                {
                    if (DataGridView1.Rows[i].Selected)
                    {
                        //DataGridView1.SelectedRows[i].Selected = false;
                        DataGridView1.Rows.RemoveAt(i);
                        i--;
                    }
                }
            }
        }
    }
}

我还发现一个小答案可能会在这种情况下帮助某人.DataGridView 的任何列都可以visible = false,因此可以通过以下代码访问它:

Edit : I also find a small answer maybe helps someone in such a case. DataGridView's any column can be visible = false so it'll be accessible by code such as :

int rowID = int.Parse(DataGridView1[0, selectedIndex].Value.ToString());

推荐答案

试试这个:

private void btn_Delete_Click(object sender, EventArgs e) 
{       
    if (rdb_Delete.Checked)
    {
        foreach (DataGridViewRow row in DataGridView1.SelectedRows)
        {
            //delete record and then remove from grid. 
            // you can use your own query but not necessary to use rowid
            int selectedIndex = row.Index;         

            // gets the RowID from the first column in the grid
            int rowID = int.Parse(DataGridView1[0, selectedIndex].Value.ToString());
            string sql = "DELETE FROM Table1 WHERE RowID = @RowID";

            // your code for deleting it from the database
            // then your code for refreshing the DataGridView

            DataGridView1.Rows.Remove(row);
        }
    }
}

这篇关于DataGridView 选择更改事件并从数据库中删除选定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆