2014-08-28 69 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); 
} 

通过这种方式,重新编制索引不会影响删除。