Enable KeyPress in Panel C #?

1

I have an application and it works like this.

I have a code to create TextBox dynamically when the maximum number of letters in TextBox1 is 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 textbox1 is not within Panel1 .

The textBox1 has to be inside Panel1 and the code works, but it is not working because Panel does not have KeyPress how can I solve this. Without using% Form%

asked by anonymous 18.01.2015 / 20:54

2 answers

1

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

See an example:

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

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

Font

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

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

If I understood correctly, your problem is in foreach (Object item in Controls) . When you use only Controls , you are picking up the collection of controls from your form, such as the TextBox is inside Panel , it does not appear , to get the controls from your Panel use foreach (Object item in this.panel1.Controls) . Consider using the TextChanged event as suggested in the other response.

If you find it necessary, see this link for some information on events and this that talks about cast .

    
18.02.2015 / 12:11