Preventing a new row from appearing in a DataGridView before current row is filled in?

Haider Ali Wajihi picture Haider Ali Wajihi · Apr 3, 2012 · Viewed 19.8k times · Source

I have a DataGridView in my WinForm application in C# 3.5.

AllowUserToAddNewRow property is set true. When user types any text in DataGridView, another new row is automatically added to DataGridView. I do not want this new row added until some checks are performed on the current row and all the necessary information has been filled in there.

Example : I have a DataGridView with a blank row: DataGridView with one blank row

When I begin typing a new row is added, which is too soon:

What I want is that the new row be added only after the user enters a Quantity:

Answer

Arif Eqbal picture Arif Eqbal · Apr 3, 2012

Set AllowUserToAddNewRow = false Now add a blank row initially to your datasource for eg. if you are binding the DataGridView to a DataTable called DT then just before

dataGridView1.DataSource = DT;

Do something like

 DT.Rows.Add(DT.NewRow());

This is to have one blank row initially so that the first record can be entered. Then handle the event dataGridView1.CellEndEdit, in that event write something like this:

void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 1)//The index of your Quantity Column
        {
            int qty = (int)DT.Rows[e.RowIndex][e.ColumnIndex];
            if (qty > 0)//Your logic if required
            {
                DT.Rows.Add(DT.NewRow());                    
            }
        }
    }