Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find which control raised an event, while in so called event? Visual C#

Tags:

c#

winforms

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.

like image 915
Chris Avatar asked Dec 08 '09 12:12

Chris


People also ask

What are the common controls events?

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.


1 Answers

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.

like image 96
Marc Gravell Avatar answered Sep 20 '22 05:09

Marc Gravell