events-calling-twice-error-on-datagridview

ankit goel 441 Reputation points
2023-05-26T12:34:34.6766667+00:00

I have developed a customDataGridView for my project. It is declared as follows.



public partial class CustomControl1 : DataGridView
{
    public CustomControl1()
    {
        this.KeyDown += new KeyEventHandler(CustomDataGridView_KeyDown);
       
        InitializeComponent();
    }
  protected override void OnEnter(EventArgs e)
    {
        base.OnEnter(e);
        this.CurrentCell = this.Rows[0].Cells[0];
        this.BeginEdit(true);
    }
now the form where I am using.

 public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();         
    }

    private void Form2_Load(object sender, EventArgs e)
    {
      customControl11.Focus();
 }
    private void customControl11_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {            
        if (customControl11.CurrentCell.ColumnIndex == 0) 
        {
           TextBox textBox = e.Control as TextBox;
            if (textBox != null)
            {
                textBox.TextChanged += TextBox_TextChanged; 
                textBox.KeyDown += TextBox_KeyDown; 
                textBox.Enter += TextBox_Enter;                 

            }
        }
    }

now the problem is that when I run the debugger, I found out that the code in OnEnter is running twice. what I mean is I code starts from OnEnter method, then to EditingControlShowing and then the OnEnter method runs again. I can't understand the logic behind it. If any respected member catches my error, please suggest the way to stop it.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,468 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.
8,187 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 31,001 Reputation points
    2023-05-26T13:20:24.9166667+00:00

    Same logic as with my last reply, just a different event.

    public class PayneDataGridView : DataGridView
    {
        private bool _firstTime = true;
    
        protected override void OnEnter(EventArgs e)
        {
            if (DataSource != null)
            {
                if (_firstTime)
                {
                    CurrentCell = Rows[0].Cells[1];
                    Timer timer = new Timer();
                    timer.Interval = 20;
                    timer.Tick += (ts, te) => {
                        timer.Stop();
                        BeginEdit(false);
                    };
                    timer.Start();
    
                    _firstTime = false;
                }
            }
        }
    }