Tuesday, February 4, 2014

Fire TextBox control events defined in a user control from Main Form

In a scenario where in I have created a user control which has a textbox control with private keypress event. I drag and drop the user control to my main form and then I want to fire the keypress event defined in the user control. Assuming in my main form I have this code:
Code:
private void customTextBox1_KeyPress_1(object sender, KeyPressEventArgs e)  
  {  
       //accept letters,numbers, spacebar and backspace key  
       if (char.IsLetterOrDigit(e.KeyChar) || e.KeyChar == '\b' || e.KeyChar == (char)Keys.Space)  
       {  
             e.Handled = false;  
       }  
       else  
       {  
            e.Handled = true;  
       }  
     }  
Note: customTextBox1 is the user control name and customTextBox1_KeyPress_1 is the user control keypress event. In order to trigger the keypress event of the textbox defined in the user control, call Keypress user control in the textbox keypress event handler. See code below:
Code:
     private void textBox1_KeyPress(object sender, KeyPressEventArgs e)  
     {  
       base.OnKeyPress(e);  
     }  
Note: textBox1 is the textbox control and textBox1_KeyPress() as the keypress event of the control defined inside the user control.
Cheers! Reference: StackOverflow

0 comments:

Post a Comment