0

I've datagridview in my windows application. By default the datagridview loads with 1 row. If we type something in the cell it creates another row below this row. It goes on like this. Now if someone types something and then deletes it, the row created below doesn't get deleted. I want to stop user from creating unlimited no. of rows without any data. Is it possible to restrict the datagridview to create maximum 2 such blank rows? Please suggest, how it can be done.

Sukanya
  • 1,041
  • 8
  • 21
  • 40
  • Possible duplicate of http://stackoverflow.com/questions/4849987/how-do-i-remove-the-empty-row-from-the-bottom-of-a-datagridview-control/4850020#4850020http://stackoverflow.com/questions/5593059/datagridview-automaticly-adds-new-row-why/5604432#5604432 – Developer Mar 19 '12 at 09:03

2 Answers2

0

Set the property AllowUserTAddRows=false; or through code

myDataGridView.AllowUserToAddRows = false;
Developer
  • 8,390
  • 41
  • 129
  • 238
0

It cannot be achieved automatically. You will need to do that manually. The best way to that is properly handling of cellvalidating and cellvalidated event. And cancel event if cells are empty. You can also set property AllowUserToAddRows=false and manually add new row e.g. by pressing button:

                // source is IBindingSource

                MyObject newObject = this.source.AddNew();
                DataGridViewRow row = this.dgv.Rows[this.source.IndexOf(newObject)];
                row.Selected = true;

                int maxSelectedOrder = this.source.IndexOf(newObject );
                int minSelectedOrder = this.source.IndexOf(newObject );

                int displayedRows = this.dgv.Rows.GetRowCount(DataGridViewElementStates.Displayed);
                int firstDisplayed = this.dgv.FirstDisplayedScrollingRowIndex;
                int lastDisplayed = displayedRows + firstDisplayed - 1;

                if (maxSelectedOrder - 1 > lastDisplayed && minSelectedOrder - 1 > firstDisplayed)
                {
                    int firstToDisplay = displayedRows + firstDisplayed - 1 - (displayedRows - 1);

                    if (firstToDisplay > 0)
                    {
                        this.dgv.FirstDisplayedScrollingRowIndex = firstToDisplay;
                    }
                }

                this.dgv.CurrentCell = row.Cells[0];
                this.dgv.Focus();
Marcin
  • 3,232
  • 4
  • 31
  • 48