Can anyone tell me how I could iterate through a collection of controls on a
form while assigning their event handlers to another identical collection of
controls on the same form.
So far, thanks to another programmer, I've got this working out quite nicely
for the properties:
Type ctrlType = subject.GetType ();
ConstructorInfo cInfo = ctrlType.GetCon structor(Type.E mptyTypes);
Control retControl = (Control)cInfo. Invoke(null);
foreach(Propert yInfo pInfo in
ctrlType.GetPro perties(Binding Flags.Public|Bi ndingFlags.Inst ance))
{
if (pInfo.CanWrite && (pInfo.Property Type.IsValueTyp e ||
pInfo.PropertyT ype.Name == "String"))
{
try
{
pInfo.SetValue( retControl,pInf o.GetValue(subj ect,null),null) ;
}
catch(Exception ex)
{
MessString += ("Could not assign the value of " + pInfo.Name + " to
\nObject:\t" + subject.Name + "\nOf Type:\t " + ctrlType.Name +
"\nBecause: \t" + ex.Message + "\n\n");
}
}
}
As you can see, the target controls are invoked at runtime, the above code
being called in another loop. I've also refined some code that assigns the
databindings correctly. All that is missing is that assignment of the event
handlers.
Any ideas? 9 3078
I'm not sure you're trying to do anything that couldn't be done via simple
Cloning, but the invocation list cannot be listed from outside the class
since an event creates a private instance of a delegate to hold the
invocation list. You could of course brute force it using reflection.
--
Regards,
Tim Haughton
Agitek http://agitek.co.uk http://blogitek.com/timhaughton
"Christophe r Weaver" <we*****@nospam verizon.net> wrote in message
news:%2******** *******@tk2msft ngp13.phx.gbl.. . Can anyone tell me how I could iterate through a collection of controls on
a form while assigning their event handlers to another identical collection
of controls on the same form.
So far, thanks to another programmer, I've got this working out quite
nicely for the properties:
Type ctrlType = subject.GetType (); ConstructorInfo cInfo = ctrlType.GetCon structor(Type.E mptyTypes); Control retControl = (Control)cInfo. Invoke(null); foreach(Propert yInfo pInfo in ctrlType.GetPro perties(Binding Flags.Public|Bi ndingFlags.Inst ance)) { if (pInfo.CanWrite && (pInfo.Property Type.IsValueTyp e || pInfo.PropertyT ype.Name == "String")) { try { pInfo.SetValue( retControl,pInf o.GetValue(subj ect,null),null) ; } catch(Exception ex) { MessString += ("Could not assign the value of " + pInfo.Name + " to \nObject:\t" + subject.Name + "\nOf Type:\t " + ctrlType.Name + "\nBecause: \t" + ex.Message + "\n\n"); } } }
As you can see, the target controls are invoked at runtime, the above code being called in another loop. I've also refined some code that assigns
the databindings correctly. All that is missing is that assignment of the
event handlers.
Any ideas?
Tim Haughton wrote: You could of course brute force it using reflection.
Are you sure about that? I remember trying it once, and although I didn't
give it too much time, I had the impression that the invocation list was
actually extremely well protected and couldn't be accessed, even by
Reflection. It's well possible that I missed something, but could you
please show how to do that if you know it?
Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog
"Oliver Sturm" <ol****@sturmne t.org> wrote in message
news:xn******** *******@msnews. microsoft.com.. . Are you sure about that? I remember trying it once, and although I didn't give it too much time, I had the impression that the invocation list was actually extremely well protected and couldn't be accessed, even by Reflection. It's well possible that I missed something, but could you please show how to do that if you know it?
Hi Oliver, if we're not talking at cross purposes, this should do it...
using System;
using System.Reflecti on;
namespace ConsoleApplicat ion2
{
class Class1
{
[STAThread]
public static unsafe void Main(string[] args)
{
Class2 bob = new Class2( "Bob" );
bob.MyEvent +=new EventHandler(Ha ndler);
bob.Fire();
Class2 bill = new Class2( "Bill" );
FieldInfo field = bob.GetType().G etField( "MyEvent",
BindingFlags.No nPublic | BindingFlags.In stance );
EventHandler eh = field.GetValue( bob ) as EventHandler;
bill.MyEvent += new EventHandler(eh );
bill.Fire();
}
private static void Handler( object sender, EventArgs e )
{
Class2 c = sender as Class2;
Console.WriteLi ne( "Handler called by " + c.name );
}
}
public class Class2
{
public string name;
public event EventHandler MyEvent;
public Class2( string name )
{
this.name = name;
}
public void Fire()
{
MyEvent( this, EventArgs.Empty );
}
}
}
--
Regards,
Tim Haughton
Agitek http://agitek.co.uk http://blogitek.com/timhaughton
Tim Haughton wrote: FieldInfo field = bob.GetType().G etField( "MyEvent", BindingFlags.N onPublic | BindingFlags.In stance );
Thanks for the sample! Now, if this line was working in my own test
program like it does in yours, I wouldn't have had a problem with this
before :-) Two things:
1. How did you get the idea that you have to use NonPublic, although the field in question is defined public in Class2? I tried it and it doesn't work if you use Public instead, but I really can't guess why.
2. For some reason, in my sample this doesn't work - this was one of the things I tried myself. The thing is, I was trying to access the Click event handlers for a normal System.Windows. Forms.Button. The click event on that one (or rather, on the Control) is declared as a property, not a field. Now, given your sample, I tried again using all permutations of GetProperty and Public or NonPublic flags, and just for the fun of it I fell back on GetField and GetEvent :-) No go. I'm still assuming I'm missing some combination here... any ideas?
Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog
Oliver Sturm wrote: 1. How did you get the idea that you have to use NonPublic, although the field in question is defined public in Class2? I tried it and it doesn't work if you use Public instead, but I really can't guess why.
It isn't public, it's private. Fire up ILDasm or better, .Net Reflector
and have a look at my sample compiled into an assembly. There is a
public event, yes. But there's also a *private* EventHandler delegate
declared as an instance with the same name(MyEvent). Declaring the
event is essentially syntactic sugar. What's really happening is you're
creating a private EventHandler delegate, and creating public add and
remove methods to add and remove handlers. Essentially we're wrapping
the private EventHandler delegate up so clients can only use the += and
-=, i.e. the add and remove. Have a look under the hood and all becomes
clear. The add method simply combines the passed in delegate with the
existing delegate.
2. For some reason, in my sample this doesn't work - this was one of the things I tried myself. The thing is, I was trying to access the Click event handlers for a normal System.Windows. Forms.Button. The click event on that one (or rather, on the Control) is declared as a property, not a field. Now, given your sample, I tried again using all permutations of GetProperty and Public or NonPublic flags, and just for the fun of it I fell back on GetField and GetEvent :-) No go. I'm still assuming I'm missing some combination here... any ideas?
I've not looked at the Button class in depth, and my wife is glaring at
me because I'm supposed to be cooking tea ;) (Are you sure it's a
property?) But... I think it falls down to the same principle. If you
declare a public event, you're also committing to having a private
delegate, i.e. you're also committing to an implementation.
Like I said before, open up my sample in reflector, have a look at it.
Decompile it and see what's really happening.
--
Regards,
Tim Haughton
Agitek http://agitek.co.uk http://blogitek.com/timhaughton
Hi Oliver, FYI I've written this solution up... http://www.blogitek.com/timhaughton/...g_the_eve.html
--
Regards,
Tim Haughton
Agitek http://agitek.co.uk http://blogitek.com/timhaughton
"Oliver Sturm" <ol****@sturmne t.org> wrote in message
news:xn******** ********@msnews .microsoft.com. .. Tim Haughton wrote:
FieldInfo field = bob.GetType().G etField( "MyEvent", BindingFlags.N onPublic | BindingFlags.In stance ); Thanks for the sample! Now, if this line was working in my own test program like it does in yours, I wouldn't have had a problem with this before :-) Two things:
1. How did you get the idea that you have to use NonPublic, although the
field in question is defined public in Class2? I tried it and it doesn't
work if you use Public instead, but I really can't guess why. 2. For some reason, in my sample this doesn't work - this was one of the
things I tried myself. The thing is, I was trying to access the Click event
handlers for a normal System.Windows. Forms.Button. The click event on that
one (or rather, on the Control) is declared as a property, not a field. Now,
given your sample, I tried again using all permutations of GetProperty and
Public or NonPublic flags, and just for the fun of it I fell back on
GetField and GetEvent :-) No go. I'm still assuming I'm missing some
combination here... any ideas?
Oliver Sturm -- omnibus ex nihilo ducendis sufficit unum Spaces inserted to prevent google email destruction: MSN oliver @ sturmnet.org Jabber sturm @ amessage.de ICQ 27142619 http://www.sturmnet.org/blog
Hi Oliver, FYI I've written this solution up... http://www.blogitek.com/timhaughton/...g_the_eve.html
--
Regards,
Tim Haughton
Agitek http://agitek.co.uk http://blogitek.com/timhaughton
"Oliver Sturm" <ol****@sturmne t.org> wrote in message
news:xn******** ********@msnews .microsoft.com. .. Tim Haughton wrote:
FieldInfo field = bob.GetType().G etField( "MyEvent", BindingFlags.N onPublic | BindingFlags.In stance ); Thanks for the sample! Now, if this line was working in my own test program like it does in yours, I wouldn't have had a problem with this before :-) Two things:
1. How did you get the idea that you have to use NonPublic, although the
field in question is defined public in Class2? I tried it and it doesn't
work if you use Public instead, but I really can't guess why. 2. For some reason, in my sample this doesn't work - this was one of the
things I tried myself. The thing is, I was trying to access the Click event
handlers for a normal System.Windows. Forms.Button. The click event on that
one (or rather, on the Control) is declared as a property, not a field. Now,
given your sample, I tried again using all permutations of GetProperty and
Public or NonPublic flags, and just for the fun of it I fell back on
GetField and GetEvent :-) No go. I'm still assuming I'm missing some
combination here... any ideas?
Oliver Sturm -- omnibus ex nihilo ducendis sufficit unum Spaces inserted to prevent google email destruction: MSN oliver @ sturmnet.org Jabber sturm @ amessage.de ICQ 27142619 http://www.sturmnet.org/blog
Hi Tim,
so, I know now why I didn't find the problem myself at the time. I didn't
take the time to actually analyze the issue in detail, with a sample like
yours - which shows significant differences to the Button sample I was
working with.
Obviously you are right about the visibility of the relevant member. The
problem is that the Button class, for instance, doesn't even have such a
member because it uses the Component.Event s list for its events instead of
its own member.
My train of thought was really different at the time, and that's still
valid right now: I was trying to find a generic way to copy the invocation
list from a control's event, of which I would know nothing more than the
name. For example, I have a control with an event called "Click" - I want
to copy the invocation list from that one.
This still seems to be impossible, because the way to do it in each single
instance depends on a lot of implementation details. For example: in your
sample, it's enough to access a private member; in the Button case, I'd
have to access a private static member, which is used as a key into the
Events list, get the Events list itself and then I'd be able to read the
invocation list from it - for any other control, things might work
differently again. Nice to know that it's generally possible, but that
wasn't the generic solution I was originally looking for :-)
Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog
Hi Tim,
so, I know now why I didn't find the problem myself at the time. I didn't
take the time to actually analyze the issue in detail, with a sample like
yours - which shows significant differences to the Button sample I was
working with.
Obviously you are right about the visibility of the relevant member. The
problem is that the Button class, for instance, doesn't even have such a
member because it uses the Component.Event s list for its events instead of
its own member.
My train of thought was really different at the time, and that's still
valid right now: I was trying to find a generic way to copy the invocation
list from a control's event, of which I would know nothing more than the
name. For example, I have a control with an event called "Click" - I want
to copy the invocation list from that one.
This still seems to be impossible, because the way to do it in each single
instance depends on a lot of implementation details. For example: in your
sample, it's enough to access a private member; in the Button case, I'd
have to access a private static member, which is used as a key into the
Events list, get the Events list itself and then I'd be able to read the
invocation list from it - for any other control, things might work
differently again. Nice to know that it's generally possible, but that
wasn't the generic solution I was originally looking for :-)
Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619 http://www.sturmnet.org/blog This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Sandor Heese |
last post by:
Question,
When using BeginInvoke (on a From to marshal to the UI thread) with the
EventHandler delegate I see some strange behaviour. The problem is that I
call the UpdateTextBox method with a class derived from EventArgs ( i.e.
MyEventArgs) and when the BeginInvoke is called and the UpdateTextBox
methode is call on the UI thread the parameter e (EventArgs) does not
contain the derived MyEventArgs object but a EventArgs object.
The...
|
by: dominosly |
last post by:
Okay, this is a rather complicated problem, so here is the short of
it:
I am using a custom designed user control that simply writes out a
plain old html submit button to the page. When the page posts back it
will randomly (I'm talking a few out of a hundred times) not catch the
System.EventHandler on the submit button click.
Here are the details:
|
by: Torben |
last post by:
For test purposes I attach an event to a control, say a TextBox
TextChanged event. At another time the same event delegate is attached
to some other control, maybe a listbox.
Same event function every where. The event function should happen only
once for that control (and then, maybe again if it is attached to the
control again).
Could I make that deattachment operation general? could the function
find out what event it is attaced?...
|
by: DotNetJunky |
last post by:
I have built a control that runs an on-line help system. Depending on the
category you selected via dropdownlist, it goes out and gets the child
subcategories, and if there are any, adds a new dropdownlist to the screen
for selection. This continues until there are no children, and then it
checks for a help article list based on that last selection and displays
actual articles for display.
Adding the controls and getting everything...
|
by: Alessandro Rossi |
last post by:
Hi,
I am having this problem:
I have developed a composite component which has 2 components: a textbox and a button.
I need to add an eventhandler to a button click. I have added the eventhandler, in the CreatechildControls override, but it doesn't work.
this is the code:
namespace Space1
{
public class LookUp: System.Web.UI.WebControls.WebControl , INamingContainer
{
| |
by: mawi |
last post by:
Hi there,
When removing page children controls created dynamically
not in last-to-first order, the close button of the last
control looses its event wiring, even though the handler is
rewired on each postback. It needs one postback roundtrip
to "get it back".
Form has an "add panel" button. Using it I dynamically add
3 panels with a remove button on each, A B C, to the page.
|
by: Vi |
last post by:
Hi,
I'm building a screen where I want to allow users to be able to see data one
page at a time.
The users would view the data by clicking on the Page Nr.
The problem is that the number of pages is dynamic, based on how much data
the database returns, and I'm having troubles building the list of page
numbers.
I'm trying to build it using LinkButton controls, but because their number
is dynamic, I don't know how to link their handlers to...
|
by: OfurGørn |
last post by:
At runtime I generate 8 pictureboxes, when the user click on a picturebox I
fire an onclick eventhandler. Because these pictureboxes are generate at
runtime I do not have direct access to the their name property.
I need to know the name of the picturebox that the user click on so my
question is,
is it possible to pass data with en evenhandler like onclick? or is there a
another approach to
this that I am missing?
--
|
by: moondaddy |
last post by:
C# 2.0
I have declared some event arguments like this:
public class ModeStateChangedEventArgs : EventArgs
{
Gen.DataState myState;
public ModeStateChangedEventArgs() { }
|
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...
|
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,...
| |
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...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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...
|
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...
|
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();...
| |
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...
| |