Remove Uncommitted New Rows Of DGV

2020-04-02 08:36发布

I have unbound DGV and I wants to remove unwanted last row of it on DGV Leave EventHandller. How to do it?.

I know to add new rows to dgv by programmatically and setting the property AllowUserToAddRows = false.

But my question is : is it possible to remove last row of DGV without setting property AllowUserToAddRows = false?.

OR

Is it possible to remove uncommitted new rows of DGV?

5条回答
够拽才男人
2楼-- · 2020-04-02 08:40

Set the DataGridView AllowUserToAddRows property to False.

However you'll have to provide a method which will allow the user to enter a new row. For example you can have that when the user double click the DataGridView, you set AllowUserToAddRows to true. And then when they are done editing, you set the value back to False.

To Add a new Row:

Lets say your DataGridView is called MyDataGridView and you have a Button called BtnAddRow and when the button is clicked, it adds an new row to your DataGridView.

private void btnAddRow_Click(object sender, RoutedEventArgs e)
{
       // Add an empty row
       MyDataGridView.Rows.Add();
}

Alternatively, you could just handle DataGridView OnDoubleClick event in which you can call MyDataGridView.Rows.Add() to add a new row.

查看更多
女痞
3楼-- · 2020-04-02 08:52

If your DataGridView is bound to a DataSet, this does the trick for deleting the current row:

If DataGridView1.CurrentRow.IsNewRow Then
    MyDataSet1.MyTable.Rows(DataGridView1.CurrentRow.Index).RejectChanges()
Else
    DataGridView1.Rows.Remove(DataGridView1.CurrentRow)
End If
查看更多
太酷不给撩
4楼-- · 2020-04-02 08:57

I want to remove last row on DGV Leave Event.

Just attach an handler on DataGridView.Leave event and use this code:

private void MyHandler(object sender, EventArgs e)
{
     int count = dgv.Rows.Count;
     dgv.Rows.RemoveAt(count - 1);
}

EDIT: Are you referring to the last blank row that appears in the DataGridView? If yes it is there to allow the user to create new rows. To disable it follow the suggestion of Jean-Luis setting AllowUserToAddRows property to false.

查看更多
混吃等死
5楼-- · 2020-04-02 08:59

You can remove uncommitted new rows in datagrid view by setting AllowUserToAddRows = false

grid.AllowUserToAddRows = false;

查看更多
啃猪蹄的小仙女
6楼-- · 2020-04-02 09:03

I had the same problem with removing the "last" row from a DataGridView. I solved it like this.

grid.Rows.RemoveAt(grid.Rows.Count - 2);

It skips the last row which is the uncommitted new row that throws an exception if you try to remove it.

To remove several rows:

while (new_count < grid.Rows.Count - 1)
{
    grid.Rows.RemoveAt(grid.Rows.Count - 2);
}

Therefore, no need to set AllowUserToAddRows = false.

查看更多
登录 后发表回答