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.
Using CellEndEdit event, I tried to:
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.