deleting the last uncommited row inside datagridview

rahul kumar 605 Reputation points
2023-07-09T14:02:17.6266667+00:00
  protected override bool ProcessDialogKey(Keys keyData)
        {
           
            int  currentrowposition = CurrentCell.RowIndex; // it must stay here
           int currentcolumnposition = CurrentCell.ColumnIndex; // it must stay here 
            if (keyData == Keys.Enter)
            {
                this.CommitEdit(DataGridViewDataErrorContexts.Commit);
                this.EndEdit();
                if(currentcolumnposition ==0 && string.IsNullOrEmpty(this.CurrentCell.Value?.ToString()))
                {                    
                    this.Rows.RemoveAt(currentrowposition);
                    this.SelectNextControl(this, true, true, true, true);
                 
                    return true;
                }

the above is the code for my datagridview . Here i am trying to remove the last row if the user is about to leave the datgridview but i am getting the following error . 'Uncommitted new row cannot be deleted.' .

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,918 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,211 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 48,691 Reputation points Microsoft Vendor
    2023-07-10T02:37:09.8466667+00:00

    Hi @rahul kumar , Welcome to Microsoft Q&A.

    As the error says, Uncommitted new row cannot be deleted..

    Here you can use the AllowUserToAddRows property, set to false.

    If you need to add it again, change it to true.

    if (currentcolumnposition == 0 && string.IsNullOrEmpty(this.CurrentCell.Value?.ToString()))
    {
        //this.Rows.RemoveAt(currentrowposition);
        this.AllowUserToAddRows = false;
        this.SelectNextControl(this, true, true, true, true);
    
        return true;
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.