2

I have a problem in window application. When I insert a record and display the records in a gridview, the gridview automatically makes one empty row. And I also use

dataGridView1.AllowUserToAddRows = false;

Please help me with an alternative solution to get rid of the empty row.

rie819
  • 1,249
  • 12
  • 19
user1727804
  • 21
  • 1
  • 2
  • Hi I am use this one code DataSet data = objAllDetail.GetAllInformation(); dataGridView1.AllowUserToAddRows = false; and this one – user1727804 Oct 30 '12 at 16:22
  • 1
    There's an answer in SO : http://stackoverflow.com/questions/4849987/how-do-i-remove-the-empty-row-from-the-bottom-of-a-datagridview-control – Thinhbk Oct 30 '12 at 16:51

2 Answers2

4

Default DGV will have a blank row at the bottom to enable user adding a new row, by setting dataGridView1.AllowUserToAddRows = false; will disable the blank row.

You may delete the blank rows manually like this:

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--;
    }   
 }

HTH.

Thinhbk
  • 2,194
  • 1
  • 23
  • 34
  • 1
    the code works perfectly for me! as I want the user to add new rows but this new empty row that the user accidentally types is also saved but you code solved the problem thanks a lot – amateur programmer Aug 24 '15 at 21:37
0

Are you sure you don't have a blank record in your datasource? another way you could check this is to add an if statment on to the OnRowDataBound to check the item index which if 0 (or some other way to identify the blank row) then set the row's Visible = false

jgok222
  • 314
  • 7
  • 23