Click here to Skip to main content
14,930,087 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI All

I have Gridview in winform, I want to remove last empty row in gridview I try to use below code but it show me error

My Code
C#
bool Empty = true;

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                Empty = true;
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    if (dataGridView1.Rows[i].Cells[j].Value != null && dataGridView1.Rows[i].Cells[j].Value.ToString() != "")
                    {
                        Empty = false;
                        break;
                    }
                }
                if (Empty)
                {
                    dataGridView1.Rows.RemoveAt(i);
                }

Showing Error

Uncommitted new row cannot be deleted.

Please help me

Thanks
Posted
Updated 24-Apr-21 16:44pm

C#
for (int i = 1; i < dataGridView1.RowCount - 1; i++)
{
   Boolean isEmpty = true;
   for(int j=0;j<dataGridView1.Columns.Count; j++)
   {
     if (dataGridView1.Rows[i].Cells[j].Value.ToString() != "" )
      {
          isEmpty = false;
          break;
      }
    }
    if (isEmpty)
    {
       dataGridView1.Rows.RemoveAt(i);
       i--;
    }
 }
   
Comments
mjawadkhatri 12-Jan-15 9:10am
   
HI.
above code is not working for me.. code do nothing.. I use above code in button_click event. please help me where i do mistake

Thanks
[no name] 12-Jan-15 9:13am
   
which button click event Grid view button or form button click event
mjawadkhatri 12-Jan-15 9:17am
   
form button click event
Set AllowUsersToAddRow as false. BTW, you might want to specify DataGridView instead of GridView since latter is web control.
   
Only uncheck checkbox Enable Adding of grid data view. That is easier way without any code ..
   
v3
Comments
Richard Deeming 26-Apr-21 5:47am
   
Which is exactly what Solution 1 said, six years ago. You have added nothing to the discussion.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900