简体   繁体   中英

Prevent DataGridView from commiting a new blank row

I have an unbound DGV to which users can add rows.

By default, there's a blank row at the bottom of the grid. Let's call it row X. When the user starts editing a cell in row X, a NEW blank row is added just below it (X+1).

编辑单元格时添加了新的空白行

But after the new row is added , it's possible to delete all text in row X and leave it while its blank. The the grid is left with 2 consecutive blank rows.

离开储存格后还剩2行空白

Using CellEndEdit event, I tried to:

  1. remove row X - got an InvalidOperationException: Operation is not valid because it results in a reentrant call to the SetCurrentCellAddressCore function.
  2. remove row X+1 - got an InvalidOperationException: Uncommitted new row cannot be deleted.

Can't do it with CellValueChanged event either, as null to null isn't considered a change.

Is there a way to prevent this behavior / ensuring only one blank row exists at all times ? Thanks!

The first error is telling you that a row cannot be removed if one of its cells has the current focus. So on CellEndEdit , set the CurrentCell to a cell in the row above (before trying to remove the row).

Edit: Sample code

public class FormClick : Form {

    DataGridView dgv = new DataGridView { Dock = DockStyle.Fill };
    DataTable table = new DataTable();

    public FormClick() {
        table.Columns.Add("A");
        table.Columns.Add("B");
        dgv.DataSource = table;
        Controls.Add(dgv);

        dgv.CellEndEdit += dgv_CellEndEdit;
    }

    void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e) {

        DataRow row = ((DataRowView) dgv.Rows[e.RowIndex].DataBoundItem).Row;
        bool allEmpty = true;
        for (int i = 0; i < table.Columns.Count; i++) {
            String s = row[i].ToString();
            if (s.Length > 0) {
                allEmpty = false;
                break;
            }
        }
        if (allEmpty) {
            dgv.Rows.RemoveAt(e.RowIndex);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM