开发者

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

开发者 https://www.devze.com 2023-03-03 14:09 出处:网络
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 add开发者_JS百科s row b

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 add开发者_JS百科s row but not the end of the datagridview. is there a way to add a blank row at the end of datagridview?


The last row in datagridview is to allow user to add row if he wants.

Set DataGridView2.AllowUserToAddRows = False

Then try to use Me.DataGridView2.Rows.Add() . It will Add a raw to the end of the dataGridView


I would upvote @user1157690, but I don't have enough reputation to do so. In order to add a blank row to the bottom:

DataGridView2.AllowUserToAddRows = false;
for (int i = 0; i < 10; i++)
{ 
    DataGridView2.Rows.Add();
}
DataGridView2.AllowUserToAddRows = true;

This would allow you to enter 10 blank rows programmatically in chronological order from oldest to newest while allowing the user to enter additional rows if necessary. This is the best method that I know of for allowing user flexibility and programmer consistency.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消