简体   繁体   中英

adding new row to the bottom of datagridview

I have datagridview with one column and one record on my form and I want to add new row to the bottom of datagridview with the click of a button and populate the last cell with Rows.Count number. but it seems that when the new row is added with dataGridView1.Rows.Add() method, it is inserted to the top of current row. How can I Insert a row to the bottom of datagridview? Is this behavior expected?

Thanks.

private void button1_Click(object sender, EventArgs e)
 {

    dataGridView1.Rows[dataGridView1.Rows.Count-1].Cells[0].Value = dataGridView1.Rows.Count;
    dataGridView1.Rows.Add();

}

在此处输入图片说明

Though the question may be a duplicate , the answer provided on that question is not a sufficient solution. You'll see why.

You are operating under the idea that dataGridView1.Rows.Add(); is adding a new row at " the top of [the] current row. " This isn't quite the case. With your current setup, the following is defaulted in the designer:

this.dataGridView1.AllowUserToAddRows = true;

This results in the bottom (uncommited) row of the grid, indicated by the * symbol. This is the NewRow , as indicated in code by accessing with this.dataGridView1.NewRowIndex . Any time you edit this row, it is commited and another NewRow is added.

DGV新行

Why does that matter? Because when you have this property set to true , calling dataGridView1.Rows.Add() adds a new row to the bottom of your commited rows, before the NewRow. For example:

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.Rows[dataGridView1.Rows.Count-1].Cells[0].Value = dataGridView1.Rows.Count;
    dataGridView1.Rows.Add(new object[] { "I'm new" });   
}

添加的行

The proposed answer: dataGridView1.Rows.Insert(dataGridView1.Rows.Count - 1, 1) will do the exact same thing. Hence why it isn't a solution.

Solution

Swap the order of your two lines of code.

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.Rows.Add();
    dataGridView1.Rows[dataGridView1.Rows.Count-1].Cells[0].Value = dataGridView1.Rows.Count;   
}

解决了

Try this:

private void button1_Click(object sender, EventArgs e)
{
    object[] rowData = new object[dataGridView1.Columns.Count];
    rowData[0] = dataGridView1.Rows.Count;
    dataGridView1.Rows.Add(rowData);          
}

Write Code in Row Add button click event like below

private void btnRowAdd_Click(object sender, EventArgs e)
{
    String[] row = { "", "", "", "", "", "", "" };
    dataGridView1.Rows.Add(row);
    dataGridView1.AllowUserToAddRows = false;
}

Here is row add button: 这是行添加按钮

Then also called that event in new button like below:

这是新按钮

btnRowAdd_Click(e, e);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM