我有一個方法將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
指數保持每一個行被刪除的時間變化。
我該如何做到這一點?如果保存成功,我該如何刪除一行,但如果出現錯誤則保留它?
選擇這個,因爲它是(IMO)最優雅的。擺脫額外的循環。 – Ben 2014-08-28 08:31:42