1

I have a lot of TextBoxes in my single winform application. I am looking for a way to bind a single event method to all those textboxes when the form loads or in its constructor, so I dont add the event to every single textbox in designer.

In the event, I want to detect the ENTER key and then programmatically click on a button:

private void ApplyFilterOnEnterKey(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        btnApplyFilters_Click(this, null);
    }
}

Now the problem is how can I loop over all textboxes in my form and bind them to the above method? My textboxes are everywhere, inside nested tablelayoutpanels or nested normal pannels. How this loop will look like and where should I put it? In form constructor or in load event?!

Dumbo
  • 13,555
  • 54
  • 184
  • 288

4 Answers4

1

Just use the Controls collection and look if the control is a textbox then append the event

reiti.net
  • 33
  • 3
1

Loop through all textboxes (including nested) like this as shown here: Loop through Textboxes

Then,

var allTextBoxes = this.GetChildControls<TextBox>();

foreach (TextBox tb in this.GetChildControls<TextBox>())
{
    tb.Click += ApplyFilterOnEnterKey;
}
Community
  • 1
  • 1
user879355
  • 59
  • 2
1

Instead of subscribing to every TextBox's KeyDown event, you have two other options that I think are better:

  1. Set your button as the default button of the form by setting AcceptButton property of the form to the button you want to be clicked by pressing Enter key.

  2. Override ProcessDialogKey on your form and check for pressing the Enter key:

    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.Enter)
        {
            // ... do what you want
            return true;
        }
        else
            return base.ProcessDialogKey(keyData);
    }
    
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
0
    private void TextBoxFocusIn(object sender, EventArgs e)
    {
        TextBox textBox = (TextBox)sender;
        if (textBox.Text == "Encrypted value here...")
        {
            textBox.Text = "";
            textBox.ForeColor = Color.Black;
        }
    }

    private void TextBoxFocusOut(object sender, EventArgs e)
    {
        TextBox textBox = (TextBox)sender;
        if (textBox.Text =="")
        {
            textBox.Text = "Encrypted value here...";
            textBox.ForeColor = Color.Gray;
        }
    }


    private void BindPlaceHolderInTextbox(Panel contentPanel)
    {
         foreach(Control control in contentPanel.Controls)
        {
            if(control.GetType() == typeof(TextBox))
            {
                control.Text = "Encrypted value here...";
                control.ForeColor = Color.Gray;
                control.GotFocus += new System.EventHandler(TextBoxFocusIn);
                control.LostFocus += new System.EventHandler(TextBoxFocusOut);
            }
        }
    }