473,800 Members | 2,497 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

can't wrap my mind around events

My general problem with events seems to be that there are so many parts
to them, and I'm not sure where they all go or when you use which parts.
For example, there's the delegate, the event name, the event handler,
then the coding that wires it together. For the most part, I do
understand these things, but I get confused when it comes to putting it
all together.

More specifically, here's some code from a book:

this.txtMonthly Investment.Text Changed += new
System.EventHan dler(this.txtMo nthlyInvestment _TextChanged);

First off, do you need the 'this' keyword? Second, where does this code
go? In the Load event of the form that contains the text box?

Another example:

ProductList products = new ProductList(); //an array list object

products.Change d += new EventHandler(Ch angedHandler);

Why isn't 'this' used in the second example? Is the book being
inconsistent, or is it a different situation? (In the book, it says it's
calling it from a different class, but I don't know what that means
exactly: "To handle an event from another class, you create an instance
of the class that raises the event and assign it to a class variable.")

Where does that first line go? (The declaration of products). The above
two lines are the entire example (except for the event handler itself),
so I think some stuff has been left out. It doesn't show which class
it's included in.
Basically I'm just very lost when it comes to events, and I always have.
I don't understand where all the code goes for each 'part', and that's
probably what it all comes down to, I guess.

Any help would be appreciated, or any suggestions for sites that clearly
explain events.

Thanks,
John
Nov 17 '05
11 1521
Hmm, it's starting to make a little more sense. I appreciate all this help.

I think one thing that had me confused at first (and that I see a little
more clearly now because I've seen an entire program presented in the
book I'm reading) is that I didn't realize that 'products' in one class
was different than 'products' in another class. I never realized this
because the code was presented in pieces, until I got to the end of the
chapter. Now I realize that each 'products' is a private member of its
own class, and is independent of the other.

Wavemaker wrote:
"John Salerno" wrote:
Let's say you have class A, which is a button. The event for this
class is Click. You want class B to respond to this click. Now, is
class B responding to a particular button's Click event, or just any
button that is instantiated from class A?

Depends on whether or not the event was declared as static. But we won't
go there because I think that would just make things more confusing,

So assuming the event exists at the instance level, in other words that
every instance of A has its own Click event, an instance of class B will
be responding to events from an instance of class A.

For example: I have an OK button that was created from class A, and
it's on my main form. In class B, when I'm writing the code to wire
the event to the event handler, do I need to refer to this button
specificall y, or do I simply create a new instance of A that isn't
even used in the program or anywhere on the form?

You need the instance of class A, the OK button, in order to wire it to
the instance of class B.

public class A
{
public event EventHandler Click;

// Normally, the method for raising an event is protected virtual,
// but this is just for demonstration purposes.
public void OnClick()
{
EventHandler handler = Click;

if(handler != null)
{
handler(this, EventArgs.Empty );
}
}
}

public class B
{
public B(A aInstance)
{
// Here we are connecting the event in an instance of
// class A to an instance of class B.
aInstance.Click += new EventHandler(Ha ndleClick);
}

private void HandleClick(obj ect sender, EventArgs e)
{
Console.WriteLi ne("Handled Click event.");
}
}

// Somewhere else in your application...

A a1 = new A();
B b1 = new B(a1);

A a2 = new A();
B b2 = new B(a2);

Now, an instance of class A called 'a1' is connected via the Click event
to an instance of class B called 'b1'. And an instance of class A called
a2 is connected via the Click event to an instance of class B called
'b2'.

When a1 raises its event through a call to the OnClick method, only b1
will respond to the event. Likewise, when a2 raises the Click event,
only b2 will respond.

Nov 17 '05 #11
k. first off, this was GREAT exercise for me so thanks for the
googlespace.

This compiles in Mono (Fedora 4, Mono, MonoDevelop is my new toy :) -
can't get dovecot to work!!!) but I haven't figured out abstraction in
Mono so I had to implement everything three times... but this should be
a good example of delegates. Every call made to the BroadcastSometh ing
method in the 'RadioStation' class is handled by three entirely
independant 'Radio' objects. Two of them are BackwardsStatio n, one of
them is ForwardStation.
CODE:

//************Rad ioStationTestin g.cs ---
// created on 9/6/2005 at 6:02 PM
namespace Broadcaster
{
using System.Diagnost ics;
public delegate void SendAMessage(st ring strMessage);

public class RadioStation
{
public event SendAMessage BroadcastEvent;

public RadioStation() {}

public void BroadcastSometh ing(string strMyMessage)
{
if(BroadcastEve nt != null) //This is important. Always test
//before firing
{
BroadcastEvent( strMyMessage);
}
}
} //End Class

public abstract class Radio
{
public string _strRadioName;
public Radio(RadioStat ion rsNewStation, string strRadioName)
{
_strRadioName = strRadioName;
rsNewStation.Br oadcastEvent += new
SendAMessage(Di splayBroadcast) ;
}
public abstract void DisplayBroadcas t(string strStuff);
} //End class

public class BackwardsStatio n:RadioStation
{
public string _strRadioName;
public BackwardsStatio n(RadioStation rsNewStation, string
strRadioName)
{
_strRadioName = strRadioName;
rsNewStation.Br oadcastEvent += new
SendAMessage(Di splayBroadcast) ;
}

public void DisplayBroadcas t(string strStuff)
{
string strTemp = "";
for(int i = strStuff.Length - 1; i > 0 ; i--)
{
strTemp += strStuff.Substr ing(i,1);
}
System.Console. WriteLine("Reci eved from radio " +
_strRadioName + ": " + strTemp);
}
}

public class ForwardStation: RadioStation
{
public string _strRadioName;
public ForwardStation( RadioStation rsNewStation, string
strRadioName)
{
_strRadioName = strRadioName;
rsNewStation.Br oadcastEvent += new
SendAMessage(Di splayBroadcast) ;
}

public void DisplayBroadcas t(string strStuff)
{
System.Console. WriteLine("Reci eved from radio " +
_strRadioName + ": " + strStuff);
}
}
}
/*************** *************/
namespace Testing
{
using Broadcaster;
using System.Collecti ons;
public class MyTest
{
public RadioStation _rsHeavyMetalHe aven = new RadioStation();
public ArrayList _alRadio = new ArrayList();
private RadioStation RadioStation1;
private RadioStation RadioStation2;
private RadioStation RadioStation3;

public MyTest()
{
RadioStation1 = new BackwardsStatio n(_rsHeavyMetal Heaven,
"Radio #1");
RadioStation2 = new ForwardStation( _rsHeavyMetalHe aven,
"Radio #2");
RadioStation3 = new BackwardsStatio n(_rsHeavyMetal Heaven, "Radio
#3");
}
}
}
///-----------End File
//File: Main.cs
// project created on 9/6/2005 at 6:01 PM
using System;
using Testing;

class MainClass
{
public static void Main(string[] args)
{
MyTest mt= new MyTest();
mt._rsHeavyMeta lHeaven.Broadca stSomething("Gr owl,growl...
DIE DIE DIE!");
mt._rsHeavyMeta lHeaven.Broadca stSomething("Th at was
VegetarianDogs with 'die'. " +
"And now a word from our sponsor...");
}
}

OUTPUT:
--Sorry, I can't seem to capture my console window output in Fedora...
(I suck :{ )
Back to Windows Land:
If, in VS.Net (2003) you simply moved the Testing namespace to one
project, and the Broadcast namespace to a different one and included a
reference to Broadcast in Testing, you may start to see the value in
this. I have one class (a wrapper around a serial port driver) that
fires an event that is consumed by a windows form, a class on an
independant thread and Log4Net all at the same time, in multiple
projects and namespaces...

I have a different project where a Windows User control takes an object
from an independant thread as a parameter in the constructor (much like
Radio class). Basically it allows me to talk back to any independant
control from an entirely independant thread .

NOTE:
I have found that in any class I fire an event from, I MUST wrap the
call in a "!= null" check. Otherwise if no handler for the event is
ever created, it throws an exception. (Any opinions on this?)

k. Gonna give it a rest now. Hope nobody else ever has to go through my
pain to figure out delegates again. :)

Russ

Nov 17 '05 #12

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

Similar topics

6
1936
by: lostinspace | last post by:
After four+ years of using FrontPage in a limited capacity and having created over 600 pages on my sites, I've finally (at least for the most part) abandoned FP, to begin the process of converting those pages. There are some things (a result of this transition,) which I'm not too happy about :-( I'm using 1st Page 2000. Much of my content is created in Word and then cut and pasted from Word-to-NotePad-to-the page. Formerly with FP the...
42
2057
by: Mike P. | last post by:
Hello I come from the world of C++ programming, and I'm used to writing programs that are actually executed by the CPU, and that run with some semblance of performance. I have taken the time to explore this .NET thing, and found that not only do .NET applications run extremely s-l-o-w-l-y, but the various .NET languages amount to nothing more than interpreted script languages. It is the common language run-time that actually executes your...
13
2370
by: LRW | last post by:
Having a problem getting a onSubmit function to work, to where it popsup a confirmation depending on which radiobutton is selected. Here's what I have: function checkdel() { if (document.getElementById"].value=='1') { confirm('Are you sure you want to delete this file?'); } } ......
10
4105
by: Kobu | last post by:
My question is about EOF (which is (int)-1 on the implementation I use). Type char on my implementation is 'signed' too. How is it that the input library functions that return EOF can be used properly if something like ASCII 255 is read from the input file? 255 would be returned as -1, and would be compared against EOF and cause problems. What's the point of declaring a int to hold the return
15
4058
by: Adam J. Schaff | last post by:
I have noticed that if a user closes a form via pressing return (either while the OK button has focus or if AcceptButton is set to OK for the form) then the "ENTER" keypress event fires ON THE CALLING FORM! This is very bad for me, because in my application, Form1 responds to an ENTER keypress by calling Form2. If the user closes Form2 via an ENTER, then Form1 just reopens it again, kind of trapping the user in Form2 (they can still close...
6
4904
by: scottyman | last post by:
I can't make this script work properly. I've gone as far as I can with it and the rest is out of my ability. I can do some html editing but I'm lost in the Java world. The script at the bottom of the html page controls the form fields that are required. It doesn't function like it's supposed to and I can leave all the fields blank and it still submits the form. Also I can't get it to transfer the file in the upload section. The file name...
10
2431
by: Benton | last post by:
Hi there, I have a UserControl with a couple of textboxes and a couple of buttons ("Save" and "Cancel"). The Click event for this buttons is in the UserControl's codebehind of course, so here's my question. Once the UserControl is dropped onto the container page, how can I perform some action on the codebehind of the container page from the codebehind of the UserControl? For instance, suppose that the UserControl is dropped inside one...
1
14182
by: maya | last post by:
hi, I have to do a page where there's a paragraph with an img on top left and the text in paragr has to wrap around the image.. pls see screen-shot here... http://www.mayacove.com/css/ss_page.jpg the image itself will be inserted dynamically via a CMS.. but NOT the border around it.. there are no. of ways to do the border, of course (div, table, etc..) problem is how do you make the text wrap around a table or a div?
8
10686
by: Skeer | last post by:
This is what I'm having problems with: I have a image that is in an absolute positioned div at the bottom left of my content. I want the content to be full width until reaching the image then wrap around it. Refer to the image for details: http://img31.imageshack.us/img31/3039/wrap.png The red is the content div with padding, the black is the div + image, and the white is the content. I want the text to only be in the white spot and wrap...
0
9691
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10507
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
10279
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
10036
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6815
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5473
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
5607
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4150
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
3
2948
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.