简体   繁体   中英

How to get the row index of multiple checked in checkbox column of datagridview C#

I am trying to remove a all marked/checked rows in an unbound datagridview. The checkbox column was added programatically. I know that I have to use

RequestedEmpGrid.Rows.Remove(RequestedEmpGrid.Rows[ForRequestRow.Index]);

to remove the row from the grid. However, I am having trouble getting the row index of the multiple checked rows in the datagridview. My looping is not working. Help?

                    //REMOVE ALL CHECKED
                    foreach (DataGridViewRow ForRequestRow in RequestedEmpGrid.Rows)
                    {
                        if (Convert.ToBoolean(ForRequestRow.Cells[MarkColumn.Name].Value) == true)
                        {
                            RequestedEmpGrid.Rows[ForRequestRow.Index].Selected = true;
                            RequestedEmpGrid.Rows.Remove(RequestedEmpGrid.Rows[ForRequestRow.Index]);
                        }
                    }

Why dont you try

RequestedEmpGrid.Rows.Remove(ForRequestRow)

It will just remove the row from gridview but not from Data source, so do not rebind the gridview as it will add the deleted rows again.

And if you want to delete from datasource as well just delete the selected rows from DB and then rebind the gridview.

You can try this code:

foreach (DataGridViewRow requestRow in RequestedEmpGrid.Rows)
{
    if (Convert.ToBoolean(requestRow.Cells[MarkColumn.Name].Value))
    {
        RequestedEmpGrid.Rows.Remove(requestRow);
    }
}

or this:

foreach (DataGridViewRow requestRow in RequestedEmpGrid.Rows)
{
    if (Convert.ToBoolean(requestRow.Cells[MarkColumn.Name].Value))
    {
        RequestedEmpGrid.Rows.RemoveAt(requestRow.Index);
    }
}

update : How about that?

for (int i = RequestedEmpGrid.Rows.Count; i >= 0; i--)
{
    var row = RequestedEmpGrid.Rows[i];
    if (Convert.ToBoolean(row.Cells[MarkColumn.Name].Value))
    {
        RequestedEmpGrid.Rows.RemoveAt(i);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM