Datagridview event is calling again

Honey singh 20 Reputation points
2023-10-12T14:53:14.2733333+00:00

I have a form with a button named button1 and a custom datagridview . on its click events the following is the code written

datagridview1.Focus();

now when the datagridview gets focus due to the above line , the following method of datagridview gets invoked

        protected override void OnEnter(EventArgs e)
        {
            this.CurrentCell = this.Rows[0].Cells[0];
            this.BeginEdit(true); 
            
            base.OnEnter(e);
        }

here is the problem ,

when the control reaches

 this.BeginEdit(true);

it invokes another another event

  protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
        {

         

            e.Control.KeyPress -= new KeyPressEventHandler(textbox_keypress);
            e.Control.TextChanged -= new EventHandler(TextBox_TextChanged);
            e.Control.KeyDown -= new KeyEventHandler(TextBox_KeyDown);
            e.Control.Enter -= new EventHandler(TextBox_Enter);
            if (this.CurrentCell.ColumnIndex == 1 || this.CurrentCell.ColumnIndex == 2) // Assuming the first column has an index of 0
            {
                TextBox textBox = e.Control as TextBox;
                if (textBox != null)
                {
                    textBox.KeyPress += new KeyPressEventHandler(textbox_keypress);
                }
            }

            else if (this.CurrentCell.ColumnIndex == 0) // Assuming the first column has an index of 0
            {
                TextBox textBox = e.Control as TextBox;
                if (textBox != null)
                {
                    textBox.TextChanged += TextBox_TextChanged; // Attach TextChanged event handler
                    textBox.KeyDown += TextBox_KeyDown; // Attach KeyDown event handler
                    textBox.Enter += TextBox_Enter;
                }
            }
            base.OnEditingControlShowing(e);
        }
upto here all good 


now when the above oneditingcontrol event finishes , for unknown reasons the control again passes to the

             this.CurrentCell = this.Rows[0].Cells[0];

which has already been executed .

why is this happening . can someone suggest a logical approach to handle it . because although a variable can be set, which can stop it from executing twice but i would like a sensible approach as there is a posibilty that there is something wrong/bug in my code .

Developer technologies | Windows Forms
Developer technologies | C#
Developer technologies | 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.
{count} votes

2 answers

Sort by: Most helpful
  1. gekka 13,346 Reputation points MVP Volunteer Moderator
    2023-10-13T03:51:56.4566667+00:00
    • Enter event is fired when itself or descendant controls got focus of windows operation system.
    • EditingControl get focus at BeginEdit.
    • EditingControl is child control in the DataGridView.

    The reason of first OnEnter is because the DataGridView got focus.
    The second reason is because the child control got focus.

    You should be able to watch that call OnEnter in UserControl when TextBox got focus with below code

    class TestControl : UserControl
    {
        public TestControl()
        {
            this.BackColor = Color.Pink;
            this.Height = 100;
            this.Width = 200;
    
            var childTextBox = new TextBox() { Height = 50, Width = 100, Multiline = true };
            this.Controls.Add(childTextBox);
        }
    
        private int count;
    
        protected override void OnEnter(EventArgs e)
        {
            int i = ++count;
    
            System.Diagnostics.Debug.WriteLine($"OnEnter A{i}\t{DateTime.Now: HH:mm:ss.fff}\t{this.Focused}");
    
            this.Controls[0].Focus();
            base.OnGotFocus(e);
    
            System.Diagnostics.Debug.WriteLine($"OnEnter B{i}\t{DateTime.Now: HH:mm:ss.fff}\t{this.Focused}");
        }
    }
    

    This behavior is by design of WinForms.

    If you call BeginEnter in OnCellEnter instead of OnEnter, it will be called only once.
    Because the focus of cell is virtual focus in the DataGridView.

    1 person found this answer helpful.
    0 comments No comments

  2. Anonymous
    2023-10-13T02:44:42.3266667+00:00

    Hi @Honey singh , Welcome to Microsoft Q&A,

    This is a behavior that cannot be called wrong.

    This is a logic it performs, and you have also verified this through debugging.

    When you call this.BeginEdit(true);, it may trigger certain events like OnEditingControlShowing, which could cause the control to regain focus.

    When a cell gains focus and enters edit mode, the CellEnter event is fired. This is an event that indicates that the user has selected a cell and started editing.

    It is recommended that you use a custom attribute to prevent secondary calls.

    You can also use event subscription and cancellation.

    private void BeginEditInDataGridView()
    {
         this.EditingControlShowing += OnEditingControlShowingHandler;
         this.BeginEdit(true);
    }
    
    private void OnEditingControlShowingHandler(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
         //Configure the relevant settings of the editing control here
    
         this.EditingControlShowing -= OnEditingControlShowingHandler;
    }
    
    

    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

Your answer

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