I am writing a C# program that takes in a bunch of parameters and does some transformations of data points and then draws them to screen.
On one of my forms I have a bunch of TextBoxes that I would all like to perform the same KeyPress event. Before I would just do a switch statement that would just take in the sender for the KeyPress event and compare it to all the TextBoxes. That method just doesn't seem very efficient to me as now I have 20+ TextBoxes.
What I would like to do is find which TextBox on the form sent the KeyPress event and get further information from that TextBox (IE its Text value, etc.). This would save me the trouble of having to do a huge switch with sender to see what TextBox it was equal too. But I have just been having the hardest time doing so.
I have looked through the System.Windows.Controls & System.Windows.Forms classes to see if I could find anything that would help me. What I was looking for was something that would let me see which control had focus. Maybe that was what I should have been searching for? I have also looked at what I can do with sender in the KeyPress event to see if I could figure out what TextBox raised the event and still no luck.
At this point I feel like I have confused myself more. Any help would be much appreciated.
Control Events There are various types of events associated with a Form like click, double click, close, load, resize, etc. Here, Handles MyBase. Load indicates that Form1_Load() subroutine handles Load event. Similar way, you can check stub code for click, double click.
The sender approach should be fine. You can, however, cast:
TextBox txt = (TextBox) sender; // or "as" if you aren't sure.
// you can also just cast to Control for most
// common properties
// perhaps look at txt.Name, txt.Text, or txt.Tag
Note that there are scenarios where the sender isn't what you think, but this is the rarity, and mainly relates to event forwarding via code like:
public event EventHandler AcceptClick {
add { acceptButton.Click += value;}
remove { acceptButton.Click -= value;}
}
here, sender
will be acceptButton
, which you can't see. Normally this isn't a problem, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With