Recognizing sender in form event...

  • Thread starter Thread starter HyperX
  • Start date Start date
H

HyperX

Hi,

How do I cancel the event out if the sender is a textbox, combobox,
checkbox etc in form level event like Form1_KeyPress??

private void Form1_KeyPress(object sender, KeyEventArgs e)
{
///
/// Figure out if the event is from Form1... and NOT from the
textbox...
/// Cancel the event out if the sender is anyone other than form or
tab.
///
}

I tried sender.GetType() and it always comes up as
"MyNamespace.WinUI.Form1" even though I pressed the key from the
TextBox.

How can I know if the sender is a textbox from the Form1_KeyPress??

Since textbox is on the form, form level event gets executed, which is
fine (or may not be fine?? since this should be handled in
TextBox_KeyPress event.)

Any help from any one is greatly appreciated.

Thanks,

HyperX.
 
Hi HyperX !!
there is the IS operator and the As Operator .. and you can use both in
your case .... basically the is operator check an object to see if it is of
some type so you would say :

(if Sender is
TextBox){
// this code will
excute if sender is really a text box
}

the other operator is the As operator , although it is a
custing operator , you still can use it in such a case , the as will
berform the custing if it can be done otherwise it will return null , you
can try to cust the sender to whatever " a textBox for example " if the
custing return null the the sender is not a textbox and cannot be custed to
a textbox ... as work as long as the object is some where on the chain of
the custed to object " you might better read about the as operator on the
online MSDN for more details .
however , in your case the is operator is more than enought for the job
,,,,
 
Mohamass,

Form1_Keypress(sender, KeyPress e) is a Form level event.

When I press a key in TextBox, we assume, the sender has to be TextBox,
right? No! I do sender.GetType() and the type is Form1!! Thats what
is annoying...

How can I disconnect control level events and form level events??

-------> The next statement is true. The previous statement is false.
<--------
 
Hi
it is a form level event fired by the Form ... the sender will always be
form one. you can; however, overload the eventArg class to wrap info about
the clicked item into the eventArg input parameter .
 
Back
Top