如何从datagrid和数据库中删除多个选中的复选框记录 [英] how to delete multiple selected checkbox record from datagrid and database

查看:47
本文介绍了如何从datagrid和数据库中删除多个选中的复选框记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Everyone,



请知道如何在C#Windows应用程序中循环数据网格并删除复选框值为true的行,就像yahoomail工作方式一样。我试过这个:



Hello Everyone,

Please does anyone know how to loop through datagrid in C# Windows application and remove rows that the checkbox values are true, the same way yahoomail works. i have tried this:

private void button1_Click(object sender, EventArgs e)
        {
            List<object > ChkedRow = new List<object >();
            DataRow dr;

            for ( int i = 0 ; i <= dataGridView1.RowCount - 1 ; i++ )
            {
                if ( Convert.ToBoolean( dataGridView1.Rows[i].Cells["chkcol"].Value ) == true )
                {
                    ChkedRow.Add( i );
                }
            }

            foreach ( int k in ChkedRow )
            {
                dr = dt.Rows[k];
                dt.Rows[k].Delete( );
                //dt.Rows.Remove(dr);
            }
        }





但上面的代码每次只能删除一条记录,我希望能够删除多条记录用户决定。谢谢



But the above code can only remove one record per time, i want to be able to remove more than one record if the user decides. Thanks

推荐答案

这是因为当你从gridview中删除一行时,下一行将取代已删除的行。这意味着如果你已经存储了索引复选框,它们是 true ,在删除一行之后,它们现在有不同的索引。我希望你很清楚。所以你可以做的是保留一个名为 countDeletedRows 的int类型变量,以保留已删除的行数。然后按如下所示删除记录。



注意:我使用 dataGridView1.Rows.RemoveAt()删除数据网格行

下面的代码将删除选中复选框的所有行



Hi, it is because when you are deleting a row from a gridview the next row will take place of the deleted row.That means if you have stored the indexes of checkboxes which are true, after deleting a row now they have different indexes. I hope it is clear to you. So what you can do is keep a int type variable called countDeletedRows to keep how many rows you have deleted.Then use it as below to delete the records.

Note : i used dataGridView1.Rows.RemoveAt() to delete a datagrid row
Below code will delete all the rows which checkboxes are checked

private void button1_Click(object sender, EventArgs e)
        {
            List<object> ChkedRow = new List<object>();
            int countDeletedRows = 0;

            for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
            {
                if (Convert.ToBoolean(dataGridView1.Rows[i].Cells["chkcol"].Value) == true)
                {
                    ChkedRow.Add(i);

                }
            }
            foreach (int k in ChkedRow)
            {
                dataGridView1.Rows.RemoveAt(k - countDeletedRows);
                countDeletedRows++;
            }
        }


这篇关于如何从datagrid和数据库中删除多个选中的复选框记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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