c# – 删除DataGridView(表)中的多行

我有一个数据“myTable”,它与DataGridView“dgv”绑定. DataGridView“dgv”有一个复选框列.我的目标是删除按钮事件中检查的行.数据表当然会更新.
现在我的代码只用于删除一行而不是多行.

感谢帮助.

private void btnDel_Click(object sender,EventArgs e)
    {
        try
        {
            if (dgv.RowCount>0)
            {
                foreach (DataGridViewRow row in dgv.Rows)
                {
                    DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
                    if (check.Value != null)
                    {
                        if ((bool)check.Value)
                        {
                            DaTarowView currentDaTarowView = (DaTarowView)dgv.CurrentRow.DataBoundItem;
                            DaTarow daTarow = currentDaTarowView.Row;

                            int n = dgv.CurrentRow.Index;
                            int intID = Convert.ToInt32(dgv.Rows[n].Cells[0].Value);
                            myTable.Rows.Remove(daTarow);
                            dgv.DataSource = myTable;

                            Int32 intVal = Convert.ToInt32(row.Cells[1].Value);
                            if (intVal == intID)
                            {
                                check.Value = null;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

解决方法

我找到了解决方案.错误是由

DaTarowView currentDaTarowView = (DaTarowView)dgv.CurrentRow.DataBoundItem;

currentDaTarowView不是选中的行.
正确的代码是:

List<DaTarow> toDelete = new List<DaTarow>(); 
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    {
                        DataGridViewRow row = dgv.Rows[i];
                        DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell;
                        if (check.Value != null && (bool)check.Value)
                        {
                            DaTarow daTarow = (row.DataBoundItem as DaTarowView).Row;
                            toDelete.Add(daTarow);
                        }
                    }
                }
                toDelete.ForEach(row => row.Delete());

谢谢大家的帮助.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...