visual-studio-2010

How do i add a row at the end of a DataGridview?


I have a datagridview2 on my form that has 4 columns and has data. I want to add a row at the end of it and fill it with data. But when i use 'Me.DataGridView2.Rows.Add()' it adds row but not the end of the datagridview. is there a way to add a blank row at the end of datagridview?


Solution

  • I tried and it adds the row at the end of the DataGridView. I dragged a DataGridView and a button in the form. Here is the code:

    private void addRowbutton_Click(object sender, EventArgs e)
    {
        dataGridView1.Rows.Add();
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
       dataGridView1.Columns.Add("ID", "Product ID");
       dataGridView1.Columns.Add("Name", "Product Name");
       dataGridView1.Columns.Add("Description", "Description");
       dataGridView1.Columns.Add("Price", "Price");
       for (int i = 0; i < 2; i++) 
       {
         DataGridViewRow row = new DataGridViewRow();
         row.CreateCells(dataGridView1);
         row.Cells[0].Value = i;
         row.Cells[1].Value = "Product " + i;
         row.Cells[2].Value = "Description of Product " + i;
         row.Cells[3].Value = "99.99";
         dataGridView1.Rows.Add(row);  
       }
    }
    

    If you populate the datagridview via databind you cannot add a row programmatically.