在 C# 中删除 datagridview 中的选定行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11324612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:25:21  来源:igfitidea点击:

Removing Selected rows in a datagridview in C#?

c#winformsvisual-c#-express-2010

提问by Hunter Mitchell

I am currently using this code:

我目前正在使用此代码:

foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
    dataGridView1.Rows.RemoveAt(item.Index);
}

I have checkmarks down the first column, but with this code, it only get the selected. How do i get the Selected CheckBoxes onlyto delete with the row?

我在第一列下有复选标记,但使用此代码,它只能选中。如何让 Selected CheckBoxes与行一起删除?

采纳答案by MoonKnight

You want something like

你想要类似的东西

for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
    if (Convert.ToBoolean(dataGridView1.Rows[i]
                          .Cells[yourCheckBoxColIndex].Value) == true)
    {
        dataGridView1.Rows.RemoveAt(i); 
    }
}

I hope this helps.

我希望这有帮助。

回答by Corné Hogerheijde

Try something like this:

尝试这样的事情:

foreach(DataGridViewRow row in this.dataGridView1.Rows)
{
    var checked = Convert.ToBoolean(row.Cells[0].Value); // Assuming the first column contains the Checkbox
    if(checked)
        dataGridView1.Rows.RemoveAt(row.Index);
}

回答by S?mmēr A?

It could be something like this... This is an example for listview, however the concept is almost there. Loop through the item and find the checkbox id and remove those selected. Hope this helps.

它可能是这样的......这是一个列表视图的例子,但是这个概念几乎就在那里。循环遍历该项目并找到复选框 ID 并删除选中的那些。希望这可以帮助。

public void btnDeleteClick(object sender, EventArgs e)
    {
        // Iterate through the ListViewItem
        foreach (ListViewItem row in ListView1.Items)
        {
            // Access the CheckBox
            CheckBox cb = (CheckBox)row.FindControl("cbxID");
            if (cb != null && cb.Checked)
            {
                // ListView1.DataKeys[item.DisplayIndex].Values[0].ToString()
                try
                {

                }
                catch (Exception err)
                {

                }
            }
        }
    }

回答by Sherif Hamdy

Try this:

尝试这个:

if (dgv.SelectedRows.Count>0)
        {
            dgv.Rows.RemoveAt(dgv.CurrentRow.Index);
        }