473,503 Members | 1,692 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

problem with Invoking an event

I am trying to invoke an event using reflection.

//////////////////////

public class Test
{
public event EventHandler NameChanged;

public void CallEvent()
{
EventInfo ei = GetType().GetEvent("NameChanged");

if(ei != null)
{
Type handlerType = ei.EventHandlerType;

MethodInfo invokeMethod = handlerType.GetMethod("Invoke");

object[] args = new object[] { this, EventArgs.Empty };

invokeMethod.Invoke(this, args);
}
}
}

////////////////

....but the Invoke method is blowing up with an unhandled TargetException.

Anyone got any ideas what I am dong wrong ?

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 16 '05 #1
4 2570
Joanna,

You say you want to invoke the *event*, and the code is trying to invoke the
*event handler*, the listener of the event. If you want to raise the event
you should call GetRaiseMethod()...

Oh, wait! Read this first:
http://www.dotnet247.com/247referenc...51/258691.aspx. Looks like you're
out of luck...

Are you trying to raise events of your own class? Then you could add
RaiseNameChanged method. If you need to raise events of BCL classes, then
you could exploit the fact that many of them use the pattern of providing a
protected On<event name> method which raises the event.

HTH,
Alexander
"Joanna Carter (TeamB)" <jo*****@nospamforme.com> wrote in message
news:eN****************@tk2msftngp13.phx.gbl...
I am trying to invoke an event using reflection.

//////////////////////

public class Test
{
public event EventHandler NameChanged;

public void CallEvent()
{
EventInfo ei = GetType().GetEvent("NameChanged");

if(ei != null)
{
Type handlerType = ei.EventHandlerType;

MethodInfo invokeMethod = handlerType.GetMethod("Invoke");

object[] args = new object[] { this, EventArgs.Empty };

invokeMethod.Invoke(this, args);
}
}
}

////////////////

...but the Invoke method is blowing up with an unhandled TargetException.

Anyone got any ideas what I am dong wrong ?

Joanna

--
Joanna Carter
Consultant Software Engineer

Nov 16 '05 #2
"Alexander Shirshov" <al*******@omnitalented.com> a écrit dans le message de
news: OW**************@tk2msftngp13.phx.gbl...
You say you want to invoke the *event*, and the code is trying to invoke the *event handler*, the listener of the event. If you want to raise the event
you should call GetRaiseMethod()...

Oh, wait! Read this first:
http://www.dotnet247.com/247referenc...51/258691.aspx. Looks like you're out of luck...
Yup, I already tried that :-)
Are you trying to raise events of your own class? Then you could add
RaiseNameChanged method. If you need to raise events of BCL classes, then
you could exploit the fact that many of them use the pattern of providing a protected On<event name> method which raises the event.


The problem I am trying to circumvent is the necessity for any object whose
properties are to be displayed in a TextBox, etc to have a
(PropertyName)Changed event fired to update the control. This means having
to have one explicitly named event per property.

Now, it is bad enough having to have these extra events in every class, but
also having to have a wrapper method as well is starting to detract from the
idea of 'automatic' data-aware controls.

My idea was to be able to have one method that raised the appropriate 'by
name' using something similar to the code I originally posted.

What is your opinion as to why I am getting the TargetException, because
apart from that, it would seem like I am doing all the steps that should be
necessary ?

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 16 '05 #3
> What is your opinion as to why I am getting the TargetException, because
apart from that, it would seem like I am doing all the steps that should
be
necessary ?


My guess you're getting the exception because nobody has subscribed to the
event. As I said before you're invoking the handler and not invoking the
event. In "normal" C# you'd write something like this:

if (NameChanged != null)
{
// Perform the equivalent of NameChanged(this, EventArgs.Empty);

foreach (Delegate handler in NameChanged.GetInvocationList())
{
handler.Invoke();
}
}

and your code just do this:

NameChanged.GetInvocationList()[0].Invoke();

(Compiled with Outlook Express but you should get the idea)

.....

But wait, I might have something for you! If I understand correctly you're
binding your own classes to controls and you don't want to add all
corresponding <property name>Changed events. If that's the case then have a
look at this excellent article:
http://www.interact-sw.co.uk/iangblo...propertychange

HTH,
Alexander

Nov 16 '05 #4
"Alexander Shirshov" <al*******@omnitalented.com> a écrit dans le message de
news: ul*************@TK2MSFTNGP15.phx.gbl...
My guess you're getting the exception because nobody has subscribed to the
event. As I said before you're invoking the handler and not invoking the
event. In "normal" C# you'd write something like this:
Well officially, the control has subscribed, but I understand that what I
was doing did not stand much chance of working.

So, I resorted to using an internal Dictionary<string, EventHandler> like
this

/////////////////////////////

public class EventTest
{
private Dictionary<string, object> values = new Dictionary<string,
object>();

protected Dictionary<string, EventHandler> events = new
Dictionary<string, EventHandler>();

public EventTest()
{
PropertyInfo[] properties = GetType().GetProperties();

foreach(PropertyInfo propInfo in properties)
{
Type[] paramTypes = new Type[] { propInfo.PropertyType };

Type testType =
typeof(TestType<>).BindGenericParameters(paramType s);

valueTypes.Add(propInfo.Name, Activator.CreateInstance(testType));
}

EventInfo[] events = GetType().GetEvents();

foreach(EventInfo ei in events)
this.events.Add(ei.Name, null);
}

private const string sChanged = "Changed";

private void AddChangedDelegate(string name, EventHandler del)
{
events[name + sChanged] += del;
}

private void RemoveChangedDelegate(string name, EventHandler del)
{
events[name + sChanged] -= del;
}

private void OnChanged(string name, EventArgs args)
{
if(events[name] != null)
events[name](this, args);
}

protected object GetValue(string name)
{
return values[name]);
}

protected void SetValue(string name, object value)
{
values[name]) = value;
OnChanged(name, EventArgs.Empty);
}

private const string sName = "Name";
private const string sAge = "Age";

public string Name
{
get { return GetValue(sName) == null ? String.Empty : (string)
GetValue(sName); }
set { SetValue(sName, value); }
}

public int Age
{
get { return (int) GetValue(sAge); }
set { SetValue(sAge, value); }
}

public event EventHandler NameChanged
{
add { AddChangedDelegate(sName, value); }
remove { RemoveChangedDelegate(sName, value); }
}
}

/////////////////////

This is much simpler, only requiring the obligatory (PropertyName)Changed
events for each property :-) + :-(

Although I am not jettisoning my code as it makes handling events not
destined for controls easier to manage.
But wait, I might have something for you! If I understand correctly you're
binding your own classes to controls and you don't want to add all
corresponding <property name>Changed events. If that's the case then have a look at this excellent article:
http://www.interact-sw.co.uk/iangblo...propertychange


Now why didn't you post that earlier !!! <vbg>

I had just finished the version above, checked the newsgroups, read this
article, picked my jaw up from the desk :-), changed my code and all is well
with the world !!!

Thank you, thank you, thank you.

I might have been doing OO design for years, but this .NET framework is just
so massive; thank goodness for the internet allowing us to 'meld minds'.

Joanna

--
Joanna Carter
Consultant Software Engineer
Nov 16 '05 #5

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

Similar topics

2
1318
by: Tim Gallivan | last post by:
Hi group, I'm having a strange problem with event handling. My project has a form with a textbox that creates 25 instances of class A when a button is clicked. Class A raises the event without...
2
2671
by: amol | last post by:
Hi, I have the following code to raise events when something gets written to the Application log. The problem I'm seeing is when a bunch of entries get written to the log at the same time (or...
3
1763
by: Wild Wind | last post by:
Hello, I made a post relating to this issue a while back, but I haven't received any answer, so here I am again. I am writing a mixed C++ dll which uses the following declaration: typedef...
5
1628
by: Dan Brill | last post by:
Hi, I'm sure this issue has been covered before but after searching around I can't find anything which deals with quite the same set of circumstances or suggests an optimal solution. The...
2
1530
by: Shiju Poyilil | last post by:
I have a link button "lButton" created dynamically at the item databound event of the data grid "datagrid1" in the footer.so i want to execute the item command event of the datagrid on clicking...
3
1388
by: clsmith66 | last post by:
I hope this is just something stupid I'm missing and someone can easily point out my error. I'm trying to do a few turorials on windows services, and the couple I found so far just create an event...
2
1940
by: shanmani | last post by:
Hi, I am developing a .NET application which will invoke the methods from different COM / .NET DLLs. While invoking methods from .NET DLLs, I am encountering the following error. I have also...
3
1615
by: Rotsey | last post by:
Hi, I am getting a Exception has been thrown by the target of an invocation error when invoking a method Here is the crux of the code. I realise it could be a few things, any one give me...
4
1365
by: Claire | last post by:
Visual Studio 2003 I have a thread running a small timeout. Rather than defining my own delegate I decided to be lazy and use a standard EventHandler delegate When OnReadMessageTimeout is...
1
1681
by: hussain123 | last post by:
Hi All, I am invoking a procedure which takes 2 IN parameters and both are dates which are passed as string.In the procedure I am using those 2 IN parameters to query the db and fetch record between...
0
7199
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,...
0
7074
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...
1
6982
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7451
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...
0
5572
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,...
1
5000
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...
0
4667
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...
0
3150
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
374
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...

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.