2014-08-28 136 views
0

我有一個方法將gridview中的每一行存儲到數據庫中,然後如果保存成功,則刪除該行;但如果它不成功(不能存儲在數據庫中),它不會刪除該行。不幸的是,我無法使排除工作正常。刪除datagridview中的行

這是我當前的代碼:

public static void SavePAC(PlantAreaCode_CreateView CView) 
{ 
    List<int> removeRows = new List<int>(); 

    // For each cell in the DataGrid, stores the information in a string. 
    for (rows = 0; rows < CView.dataGridView1.Rows.Count; rows++) 
    { 
     correctSave = false; 
     if (CView.dataGridView1.Rows[rows].Cells[col].Value != null) 
     { 
      // Creates a model, then populates each field from the cells in the table. 
      PModel = new PlantAreaCode_Model(); 
      PModel.AreaCode = Convert.ToString(CView.dataGridView1.Rows[rows].Cells[0].Value); 
      PModel.AreaName = Convert.ToString(CView.dataGridView1.Rows[rows].Cells[1].Value); 
      PModel.Comments = Convert.ToString(CView.dataGridView1.Rows[rows].Cells[2].Value); 

      // Passes the model into the Database. 
      Database_Facade.Operation_Switch(OPWRITE); 
     } 
     if (correctSave == true) // correctSave is set in the database insert method. 
     { 
      removeRows.Add(rows); 
     } 
    } 
    foreach (int i in removeRows) 
    { 
     CView.dataGridView1.Rows.RemoveAt(0); // Deletes all bar the last row, including any rows that cause errors 
    } 
} 

我也曾嘗試:

foreach (int i in removeRows) 
{ 
    CView.dataGridView1.Rows.RemoveAt(i); 
} 

但是在崩潰中途,因爲Rows指數保持每一個行被刪除的時間變化。

我該如何做到這一點?如果保存成功,我該如何刪除一行,但如果出現錯誤則保留它?

回答

1

願這幫助:

1]確保correctSave被正確修改。

2]恢復循環流,循環向後允許刪除循環處理的行,而不影響要處理的下一行的索引。

for (rows = CView.dgvCreate.Rows.Count - 1; rows >= 0 ; rows--) 

3]使用CView.dataGridView1.Rows.RemoveAt(rows);

+0

選擇這個,因爲它是(IMO)最優雅的。擺脫額外的循環。 – Ben 2014-08-28 08:31:42

1

嘗試使用不帶索引的DataGridViewRow來填充行的集合。這對我有用。

public void SavePAC(PlantAreaCode_CreateView CView) 
    { 
     List<DataGridViewRow> removeRows = new List<DataGridViewRow>(); 

     foreach (DataGridViewRow row in CView.dataGridView1.Rows) 
     { 
      correctSave = false; 
      if (row.Cells[col].Value != null) 
      { 
       // Creates a model, then populates each field from the cells in the table. 
       PModel = new PlantAreaCode_Model(); 
       PModel.AreaCode = Convert.ToString(row.Cells[0].Value); 
       PModel.AreaName = Convert.ToString(row.Cells[1].Value); 
       PModel.Comments = Convert.ToString(row.Cells[2].Value); 

       // Passes the model into the Database. 
       Database_Facade.Operation_Switch(OPWRITE); 
      } 
      if (correctSave == true) // correctSave is set in the database insert method. 
      { 
       removeRows.Add(row); 
      } 
     } 

     foreach (DataGridViewRow rowToRemove in removeRows) 
     { 
      CView.dataGridView1.Rows.Remove(rowToRemove); 
     } 
    } 
1

你必須按降序排序removeRows。

List<int> removeRowsDesc = removeRows.OrderByDescending(i => i); 

然後使用foreach循環

foreach (int i in removeRowsDesc) 
{ 
    CView.dataGridView1.Rows.RemoveAt(i); 
} 

通過這種方式,重新編制索引不會影響刪除。