Enable Keypress in Panel C#?

Asked

Viewed 264 times

1

I have an app and it works like this.

I have a code to create TextBox dynamically when the maximum amount of letters in the TextBox1 for 2.

Here is the code:

private void VerificaTextBox(int contador)
{           
   foreach (Object item in Controls)
   {
      if (item is TextBox)
      {
          if (((TextBox)item).Text == null || ((TextBox)item).Text == "")
          {
              ((TextBox)item).KeyPress += delegate
              {
                  contador++;
                  if (contador >= 2)
                  {
                      Point p = new Point();
                      p = ((TextBox)item).Location;
                      TextBox nova = new TextBox();
                      nova.Name = "pagina" + 1;
                      nova.Multiline = true;
                      nova.Height = 294;
                      nova.MaxLength = 2;
                      nova.Width = 601;
                      // Anchor the button to the bottom right corner of the form
                      nova.Anchor = (AnchorStyles.Top | AnchorStyles.Top);
                      nova.Location = new Point(((TextBox)item).Location.X, ((TextBox)item).Location.Y + ((TextBox)item).Height + 20);
                      this.panel1.Controls.Add(nova);

This Code works perfectly when the textbox1 is not inside the Panel1.

To textBox1 has to stay inside the Panel1 and the code works, only it’s not working because the Panel has not KeyPress how can I solve this. Without using the KeyPress form?

2 answers

1

If I understand correctly, your problem is in foreach (Object item in Controls). When you only use the Controls, you are picking up the collection of controls from your form, such as the Textbox is inside the Panel, he doesn’t show up, to grab the controls from his Panel utilize foreach (Object item in this.panel1.Controls). Consider using the event Textchanged as suggested in the other reply.

If you think it necessary, see that link for some information about events and that who talks about cast.

1

In fact there is even the event KeyPress() to the Panel but is not intended to be used in your code.

Take an example:

public void MyKeyPressEventHandler(Object sender, KeyPressEventArgs e)
{
    // Fazer algo aqui
}

....  
...
(panel1 as Control).KeyPress += new KeyPressEventHandler(MyKeyPressEventHandler);

Source

Instead of trying to capture the key pressed on Panel, you can check the amount of characters typed in TextBox1 and thus create another TextBox dynamically. In the event TextChanged() of TextBox1 you can do:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text.Length == 2)
            {
                // Fazer algo aqui
            }
        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.