I am trying to invoke an event using reflection.
//////////////////////
public class Test
{
public event EventHandler NameChanged;
public void CallEvent()
{
EventInfo ei = GetType().GetEv ent("NameChange d");
if(ei != null)
{
Type handlerType = ei.EventHandler Type;
MethodInfo invokeMethod = handlerType.Get Method("Invoke" );
object[] args = new object[] { this, EventArgs.Empty };
invokeMethod.In voke(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 4 2580
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
RaiseNameChange d 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*****@nospam forme.com> wrote in message
news:eN******** ********@tk2msf tngp13.phx.gbl. .. I am trying to invoke an event using reflection.
//////////////////////
public class Test { public event EventHandler NameChanged;
public void CallEvent() { EventInfo ei = GetType().GetEv ent("NameChange d");
if(ei != null) { Type handlerType = ei.EventHandler Type;
MethodInfo invokeMethod = handlerType.Get Method("Invoke" );
object[] args = new object[] { this, EventArgs.Empty };
invokeMethod.In voke(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
"Alexander Shirshov" <al*******@omni talented.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 RaiseNameChange d 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)C hanged 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
> 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(thi s, EventArgs.Empty );
foreach (Delegate handler in NameChanged.Get InvocationList( ))
{
handler.Invoke( );
}
}
and your code just do this:
NameChanged.Get InvocationList( )[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
"Alexander Shirshov" <al*******@omni talented.com> a écrit dans le message de
news: ul************* @TK2MSFTNGP15.p hx.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<stri ng, EventHandler> like
this
/////////////////////////////
public class EventTest
{
private Dictionary<stri ng, object> values = new Dictionary<stri ng,
object>();
protected Dictionary<stri ng, EventHandler> events = new
Dictionary<stri ng, EventHandler>() ;
public EventTest()
{
PropertyInfo[] properties = GetType().GetPr operties();
foreach(Propert yInfo propInfo in properties)
{
Type[] paramTypes = new Type[] { propInfo.Proper tyType };
Type testType =
typeof(TestType <>).BindGeneric Parameters(para mTypes);
valueTypes.Add( propInfo.Name, Activator.Creat eInstance(testT ype));
}
EventInfo[] events = GetType().GetEv ents();
foreach(EventIn fo ei in events)
this.events.Add (ei.Name, null);
}
private const string sChanged = "Changed";
private void AddChangedDeleg ate(string name, EventHandler del)
{
events[name + sChanged] += del;
}
private void RemoveChangedDe legate(string name, EventHandler del)
{
events[name + sChanged] -= del;
}
private void OnChanged(strin g 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 { AddChangedDeleg ate(sName, value); }
remove { RemoveChangedDe legate(sName, value); }
}
}
/////////////////////
This is much simpler, only requiring the obligatory (PropertyName)C hanged
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 error, I have proved this by having it use
a streamwriter to create and write to a simple text file after raising the
event. Twenty-five files are...
|
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 within a couple of
seconds of each other). I receive an event for the first entry, but
the events for the other entries aren't triggered until...
|
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 System::Byte ByteArray __gc;
|
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 issue is, broadly, that when I try to write to the Windows Event Log
from ASP.NET code I receive a System.Security.SecurityException ("Requested...
|
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 the dynamicaly created link
button, but when at runtime i click the dymanic created control it disapears
from the datagrid footer and then it doesnt...
| |
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 log and write an entry on start
and stop. I build the projects and install them fine, but when I run the
service it starts and stops instantly. ...
|
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 included the detail of the
error stack trace and the code that I have written to invoking the methods.
I would appreciate if you could let me know...
|
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 an idea where
to start looking.
|
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 called, "sender" appears to points to the form
that started the thread rather than Thread.CurrentThread.Name.
What is going wrong please?
...
|
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 those two dates.
In java I m doin something like:-
String s_dt= "14/03/2006 09:30:30";
String e_dt= "15/04/2008 09:30:30";
String query =...
|
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...
| |
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. ...
|
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...
|
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...
|
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...
|
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...
|
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...
| |
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |