简体   繁体   中英

Deleting multiple rows in datagridview

I need to delete top 1000 rows in a datagridview.

delegate void DeleteRowsCallback(); 
    private static void Delete1KRows()
    {
        JSONTest form = (JSONTest)Application.OpenForms["JSONTest"];
        if (form.GridTestReport.InvokeRequired)
        {
            DeleteRowsCallback d = new DeleteRowsCallback(Delete1KRows);
            form.GridTestReport.Invoke(d);

        }
        else
        {
            for (int i = 0; i < 1000; i++ )
            {
                form.GridTestReport.Rows.RemoveAt(0);

            }
        }

    }

This deletes the rows but takes lot of time. Also the UI is non-responsive when the delete is in progress. Any better way to delete multiple rows.

Thanks

As you are not using any binding or virtual mode, everytime you remove a row, the entire grid is refreshed. It would be painfully slow.

As you are dealing with large amount of data, use Virtual Mode to efficietly update the grid.

See this MSDN link for more information. There is a Walkhrough available. It takes little time to setup but once it is done it would much faster ane makes life easier.

Also see Best Practices for Scaling the Windows Forms DataGridView Control to get the maximum out DataGridView .

There is my working solution. First delete the rows in database and then refill datagridview. NOTE: I use database access (oledbcommand, oledbconnection, etc...), change for your connection.

try
{
    //connectDB is the procedure to connect to database:
    connectDB();
    //this delete first the selected rows in database, and then update datagrid
    int countRows = dataGridView1.SelectedRows.Count;
    for (int i = 0; i < countRows; i++)
    {
        int currentRow = dataGridView1.SelectedRows[0].Index;
        //con.oledbcon is the conecction is the OleDbConnection procedure, miTable = name of your table
        OleDbCommand com = new OleDbCommand("DELETE FROM miTable WHERE Id=" + dataGridView1.SelectedRows[0].Cells[0].Value.ToString(), con.oledbcon);
        // delete from database
        com.ExecuteNonQuery();
        // THIS IS THE KEY!!! deselect the last row selected to be able to delete the next row in the next loop
        dataGridView1.Rows[currentRow].Selected = false;
    }
    // all OK
    MessageBox.Show("Rows deleted!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
    //in case of error
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
    //disconnectDB is the procedure to disconnect to database:
    disconnectDB();
    // and finally, refill datagrid again
    loaddatagrid();
}

When DataGridView activities run slowly in my projects, it is usually because one or more columns are configured to auto-size, and this auto-sizing happens over the whole grid as each row is deleted. To prevent it, I use code similar to the following:

Before the mass deletion:

var autoSizeModes = grid.Columns.Cast<DataGridViewColumn>).ToDictionary(col => col, col => col.AutoSizeMode);
foreach (var column in autoSizeModes.Keys)
    column.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;

After the mass deletion:

foreach (var column in autoSizeModes)
    column.Key.AutoSizeMode = column.Value;

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