473,623 Members | 2,693 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting a 'sender' argument in an event handler

Jay
I'm using VS 2005 C# Express.

I have an event handler that is called when the text cursor leaves one of many different text boxes.
When this is called, I want the text colour in that text box to change to Red. I assume that the
"sender" argument in the call is the text box that triggered the event. When I tried to change the
text colour using sender.ForeColo r = System.Drawing. Color.Red; I get a compile error: 'object' does
not contain a definition for 'BackColor'. This didn't surprise me since I'm a C# beginner. Is there
some sort of cast I can use to make it work, or do I have to use if... else if... etc statements to
check for each of the text boxes that might have triggered the event (eg one is called tbxFbeg)?
Here's a fragment of my code...

private void tbxSettingsSa_L eave(object sender, EventArgs e){
sender.ForeColo r = System.Drawing. Color.Red; //get compile error: 'object' does not contain a
definition for 'BackColor'
// sender is a textbox. The following line works OK...
// tbxFbeg.ForeCol or = System.Drawing. Color.Red;
}
Dec 20 '06 #1
6 8442
You need to cast the object first.

TextBox myTextBox = (TextBox)sender ;

/Niklas

Jay skrev:
I'm using VS 2005 C# Express.

I have an event handler that is called when the text cursor leaves one of many different text boxes.
When this is called, I want the text colour in that text box to change to Red. I assume that the
"sender" argument in the call is the text box that triggered the event. When I tried to change the
text colour using sender.ForeColo r = System.Drawing. Color.Red; I get a compile error: 'object' does
not contain a definition for 'BackColor'. This didn't surprise me since I'm a C# beginner. Is there
some sort of cast I can use to make it work, or do I have to use if... else if... etc statements to
check for each of the text boxes that might have triggered the event (eg one is called tbxFbeg)?
Here's a fragment of my code...

private void tbxSettingsSa_L eave(object sender, EventArgs e){
sender.ForeColo r = System.Drawing. Color.Red; //get compile error: 'object' does not contain a
definition for 'BackColor'
// sender is a textbox. The following line works OK...
// tbxFbeg.ForeCol or = System.Drawing. Color.Red;
}
Dec 20 '06 #2
Yep; a straight cast... for bullet-proofing I'll illustrate the case
where you *hope* is is a textbox, but aren't sure...

TextBox tb = sender as TextBox;
if(tb!=null) { // sender was (as expected) a TextBox
tb.ForeColor =System.Color.R ed;
}

Of course, if your handler only ever deals with a single control, you
can code directly against the field (as per your "this works"
example).

Marc
Dec 20 '06 #3
Jay
Thanks Marc + Niklas for your replies. It now works.

I've also found that this works, which is a little more compact. I assume it's just as good, but do
say if it isn't (I know for sure that it is always a textbox).

((TextBox)sende r).ForeColor = System.Drawing. Color.Red;

Jay
"Jay" <nospamwrote in message news:OC******** ********@TK2MSF TNGP02.phx.gbl. ..
I'm using VS 2005 C# Express.

I have an event handler that is called when the text cursor leaves one of many different text boxes.
When this is called, I want the text colour in that text box to change to Red. I assume that the
"sender" argument in the call is the text box that triggered the event. When I tried to change the
text colour using sender.ForeColo r = System.Drawing. Color.Red; I get a compile error: 'object' does
not contain a definition for 'BackColor'. This didn't surprise me since I'm a C# beginner. Is there
some sort of cast I can use to make it work, or do I have to use if... else if... etc statements to
check for each of the text boxes that might have triggered the event (eg one is called tbxFbeg)?
Here's a fragment of my code...

private void tbxSettingsSa_L eave(object sender, EventArgs e){
sender.ForeColo r = System.Drawing. Color.Red; //get compile error: 'object' does not contain a
definition for 'BackColor'
// sender is a textbox. The following line works OK...
// tbxFbeg.ForeCol or = System.Drawing. Color.Red;
}
Dec 20 '06 #4
Then yes, that is absolutely fine. The variable approach is useful
when you want to apply more than one operation to the same object -
i.e. set a few properties rather than just one. Otherwise you need to
cast each time, or create a wrapper method (and cast the parameter to
the method).

Marc
Dec 20 '06 #5
Jay
Thanks again for your help.

Jay

"Marc Gravell" <ma**********@g mail.comwrote in message
news:%2******** *******@TK2MSFT NGP03.phx.gbl.. .
Then yes, that is absolutely fine. The variable approach is useful
when you want to apply more than one operation to the same object -
i.e. set a few properties rather than just one. Otherwise you need to
cast each time, or create a wrapper method (and cast the parameter to
the method).

Marc

Dec 20 '06 #6
Dale <da******@nospa m.nospamwrote:
I agree with Marc's initial recommendation. You should do the type checking
that the "as" statement does and then check for null.
That depends on whether it not being a TextBox will always mean there's
a coding error. If it does, the exception generated from the failed
cast is entirely appropriate - using "as" would mask the error.

I only use "as" when the cast could legitimately fail in a non-error
case.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 21 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
6169
by: Andrew | last post by:
created a custom class that is derived from TreeNode, let's call it customTreeNode. I'm trying to use the TreeViewEventArgs (for the AfterSelect event) but I cannot cast to my derived TreeNode. Here is a snip... ---code snip--- private void _TreeView_AfterSelect(object sender, TreeViewEventArgs e) { customTreeNode foo = (customTreeNode)e.Node; displayInfo(foo);
3
15239
by: Christoph Boget | last post by:
Please forgive my ignorance as I'm still new to developing w/C# (and in windows in general). So if I use the wrong terms, please bear with me. I'm using VS.NET and defining the events have been really simple. Just double-click on the event and the definition for that event (along with the method) gets written. I see that the first argument that is set up is "object sender" while the second argument varies with the particular event. ...
2
9601
by: Thorsten moeller | last post by:
hi, i am am fairly new to c# and trying to write a service to check some thing periodically. i want to use a windows service. The onStart method is starting a timer. The timer.elapsed event creates a new Handler, which is calling another method. Is it possible to give this method an argument? Code now: timer.Elapsed += new ElapsedEventHandler(requestStat);
0
1279
by: Mo | last post by:
Hi, I'm getting an error: Input string was not in a correct format This happens when I try to sort a column. It seems that the sort event handler claims that the sort expression is not in String format, but it is. Any suggestions would be greatly appreciated 'DATAGRID code:
4
11299
by: poppy | last post by:
I am having trouble creating a menu item. The Code I have: private void NewLoad(object sender, System.EventArgs e) { //error here ToolStripItem mn = (ToolStripItem)sender; } The error I get is :
6
4709
by: rn5a | last post by:
Can System.EventArgs be cast to CommandEventArgs? If so, how? Actually I want the Page_Load sub to invoke another sub which is the OnCommand event handler of a LinkButton. <script runat="server"> Sub Page_Load(obj As Object, ea As EventArgs) CallCmd(obj, ??) End Sub
4
2499
by: Me | last post by:
My form has a dynamically populated context menu, and each has the same event handler for the click event. The event need to write the text of the clicked menu item into a database, so I need to either pass that to the event handler, which I cannot figure out how to do, or access the properties of the sender, which I also cannot figure out how to do. The context menu items are a list extracted from a database, using the code below in...
7
2902
by: Christopher Pisz | last post by:
My problem is my derived class is getting called twice instead of the base and then the derived. I thought this was the purpose for virtuals and dynamic casting :/ I want my base class to have its method called and then the derived class have its method called. What am I not understanding? Int the following code, my Event Tester class is getting called twice for keyboard events when I step through the debugger:...
5
1680
by: raylopez99 | last post by:
I have a form, Form6, that has a bunch of buttons overlaid on it. I want to be able to click on any arbitrary area of the form, and if that area of the form is overlaid by a button, I want to change the color of the button to Coral, and show a MessageBox with the button name. So far, I've tried the below event handlers, and the only one that has worked is of course the named button event click, for a particular named button (button3...
0
8160
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8661
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8603
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6104
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4067
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4153
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2590
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1766
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.