【问题标题】:Delete row in DGV if int is incremented?如果 int 增加,删除 DGV 中的行?
【发布时间】:2014-09-21 11:17:07
【问题描述】:

我有一种方法可以将 datagridview 中的每一行保存到数据库中,但如果每一行被保存,我想删除它。我有这个方法:

public static void SaveMajEq(MajorEquipment_CreateView CView)
{
    rowCount = 0;
    // For each cell in the DataGrid, stores the information in a string.
    for (rows = 0; rows < CView.dgvCreate.Rows.Count; rows++)
    {
        if (CView.dgvCreate.Rows[rows].Cells[col].Value != null)
        {
            // Creates a model, then populates each field from the cells in the table.
            MeModel = new MajorEquipment_Model();
            MeModel.EquipmentNumber = Convert.ToString(CView.dgvCreate.Rows[rows].Cells[0].Value);
            MeModel.EquipmentType = Convert.ToString(CView.dgvCreate.Rows[rows].Cells[1].Value);
            MeModel.Location = Convert.ToString(CView.dgvCreate.Rows[rows].Cells[2].Value);
            MeModel.Notes = Convert.ToString(CView.dgvCreate.Rows[rows].Cells[3].Value);

            Database_Facade.Operation_Switch(OPWRITE);
        }
        CView.dgvCreate.Rows.RemoveAt(rows);
    }
    MessageBox.Show(rowCount + " Entries stored in database.");
}

rowCount 在单独的类中的 try/catch 方法中递增,因此如果发生任何事情,它不会递增。我想做的只是实现这一行:

CView.dgvCreate.Rows.RemoveAt(rows);

仅当 rowCount 每次都增加时。我不知道如何实现这一点。

【问题讨论】:

    标签: c# mysql datagridview


    【解决方案1】:

    恢复循环顺序

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

    向后循环允许删除循环处理的行而不影响要处理的下一行的索引。

    【讨论】:

    • 那么我会用它来替换我当前的for 行吗?
    • 是的,当您删除一个行时,您的实际 for 循环会跳过一行,因为当您删除 X 位置的行时,位置 X+1 的行会移动到位置 X,然后您增加索引器并跳过位于 X+1 位置的行。仍然不清楚计数器变量的作用是什么。 (我为索引器使用了名称 X 而不是您的 rows 以避免混淆)
    • 谢谢,没有意识到那的意义。计数器变量用于显示数据库中存储了多少行。我认为 可能 是一个很好的变量,用于指示是否保存了一行?不过我可能是错的
    • 好吧,假设将行保存到数据库的操作是Database_Facade.Operation_Switch(OPWRITE);,那么也许您可以返回一个布尔值 true 来表示正确的保存,或者返回 false 来表示错误。您可以增加一个局部变量并删除全局counter。 (当您可以轻松避免使用全局变量时,使用它们被认为是一种不好的做法)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多