2014-02-06 55 views
1

我需要刪除datagridview中的前1000行。在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); 

      } 
     } 

    } 

這將刪除行但花費很多時間。此外,在刪除過程中界面不響應。任何更好的方法來刪除多行。

感謝

+0

你在'Virtual'模式下使用'DataGridView'嗎?你如何將數據綁定到網格? – Junaith

+0

你的gridview有數據源嗎?爲什麼不刪除你想從它的數據源獲得的所有記錄,然後你可以調用gridview.databind()刷新UI,這樣你就不需要手動刪除gridview行。 – NomNomNom

+0

我沒有綁定gridview。我正在調用form.GridTestReport.Rows.Add()。我沒有使用虛擬模式。 –

回答

0

當你不使用任何約束力或虛擬模式,每次你刪除行,整個網格被刷新。這將是痛苦的緩慢。

當您處理大量數據時,請使用Virtual Mode來有效更新網格。

請參閱this MSDN鏈接瞭解更多信息。有一個Walkhrough可用。它需要很少的時間來設置,但一旦完成,它會快得多,使生活更輕鬆。

另請參閱Best Practices for Scaling the Windows Forms DataGridView Control以獲得最大出DataGridView

0

有我的工作解決方案。 首先刪除數據庫中的行,然後重新填充datagridview。 注意:我使用數據庫訪問(oledbcommand,oledbconnection等),更改您的連接。

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(); 
}