Dynamically assign handlers (AddHandler/AddressOf)

Is it possible to dynamically direct a particular control's event to use a 
predefined method.

For example.
I have a form which I dynamically add controls to, let's say, TextBox1, 
TextBox2 and extBox3 and a module which as 3 routines, Method1, Method2, 
Method3

When I dynamically add my controls, eg TextBox4, I want to choose which of 
the 3 methods I want mapped to which event.

I was thinking of something like this...

..
..
..
Dim objTextBox1 as new TextBox
dim NameOfRoutine$="Module.Method2"
Form.Controls.Add(objTextBox1)

Call AssignMethodToEvent(objTextBox1.GotFocus, NameOfRoutine$)
..
..
..


Can anyone help me on this? Is this possible?

Nigel

0
Utf
11/15/2009 11:45:02 AM
dotnet.languages.vb 830 articles. 0 followers. Follow

7 Replies
827 Views

Similar Articles

[PageSpeed] 38

Nigel V Thomas wrote:
> Is it possible to dynamically direct a particular control's event to use a 
> predefined method.
> 
> For example.
> I have a form which I dynamically add controls to, let's say, TextBox1, 
> TextBox2 and extBox3 and a module which as 3 routines, Method1, Method2, 
> Method3
> 
> When I dynamically add my controls, eg TextBox4, I want to choose which of 
> the 3 methods I want mapped to which event.
> 
> I was thinking of something like this...
> 
> .
> .
> .
> Dim objTextBox1 as new TextBox
> dim NameOfRoutine$="Module.Method2"
> Form.Controls.Add(objTextBox1)
> 
> Call AssignMethodToEvent(objTextBox1.GotFocus, NameOfRoutine$)
> .
> .
> .
> 
> 
> Can anyone help me on this? Is this possible?
> 
> Nigel
> 

Yes, you can do this dynamically.  Here is an example for a new 
"Button1" and a subroutine "SomeClickHandler":

         AddHandler Button1.Click, AddressOf SomeClickHandler

-- 
Mike
0
Family
11/15/2009 12:14:17 PM
Nigel V Thomas schrieb:
> Is it possible to dynamically direct a particular control's event to use a 
> predefined method.
> 
> For example.
> I have a form which I dynamically add controls to, let's say, TextBox1, 
> TextBox2 and extBox3 and a module which as 3 routines, Method1, Method2, 
> Method3
> 
> When I dynamically add my controls, eg TextBox4, I want to choose which of 
> the 3 methods I want mapped to which event.
>
> I was thinking of something like this...
> 
> ..
> ..
> ..
> Dim objTextBox1 as new TextBox
> dim NameOfRoutine$="Module.Method2"
> Form.Controls.Add(objTextBox1)
> 
> Call AssignMethodToEvent(objTextBox1.GotFocus, NameOfRoutine$)
> ..
> ..
> ..
> 
> 
> Can anyone help me on this? Is this possible?

On what does it depend which method is to be used? If the criterion can
be checked at runtime, use If..Then or Select Case.

In principle, identifiers are used for programmers, not at runtime. Period.

After that period, we have reflection. Though, if it's not the only way
to achieve an aim, it should be avoided (IMO). Therefore my question is, why
do you have an identifier that was of note for the compiler only, at runtime
in a string? Is it stored externally? It's dangerous because the compiler
can't check the validity of the name in the string.

-- 
Armin
0
Armin
11/15/2009 12:20:02 PM

"Family Tree Mike" wrote:

> Nigel V Thomas wrote:
> > Is it possible to dynamically direct a particular control's event to use a 
> > predefined method.
> > 
> > For example.
> > I have a form which I dynamically add controls to, let's say, TextBox1, 
> > TextBox2 and extBox3 and a module which as 3 routines, Method1, Method2, 
> > Method3
> > 
> > When I dynamically add my controls, eg TextBox4, I want to choose which of 
> > the 3 methods I want mapped to which event.
> > 
> > I was thinking of something like this...
> > 
> > .
> > .
> > .
> > Dim objTextBox1 as new TextBox
> > dim NameOfRoutine$="Module.Method2"
> > Form.Controls.Add(objTextBox1)
> > 
> > Call AssignMethodToEvent(objTextBox1.GotFocus, NameOfRoutine$)
> > .
> > .
> > .
> > 
> > 
> > Can anyone help me on this? Is this possible?
> > 
> > Nigel
> > 
> 
> Yes, you can do this dynamically.  Here is an example for a new 
> "Button1" and a subroutine "SomeClickHandler":
> 
>          AddHandler Button1.Click, AddressOf SomeClickHandler
> 
> -- 
> Mike
> .
> 
Mike, thanks for the reply

Unfortunately, I only know that the Button1.Click event is going to be 
handled by 'SomeClickHandler' at runtime. I have a number of 
'SomeClickHandlers' and I want the .Click event to use only one. I only know 
which one at runtime...

0
Utf
11/15/2009 1:11:01 PM
Mike, Armin

A little background (long, sorry)...

My app has many (many!) data capture forms. The forms allow the user to 
input all sorts of basic infomation, dates, times, text, currency, selections 
from dropdown lists and so on. Instead of designing each form manually I have 
created a module (minput) which exposes some properties and a method for 
input.

For example:
To display a data capture form for a user which prompts for something simple 
like a name and password (this is a very simplistic example) I do the 
following..

call mInput.AddField(FieldTitle$="Your name",FieldType.Name,DefaultValue$="")
call 
mInput.AddField(FieldTitle$="Password",FieldType.Password,DefaultValue$="")
call mInput.AddField(FieldTitle$="D.O.B.",FieldType.Date,DefaultValue$="")
I can group the fields across Tabs on a TabControl, add tooltips, reasons 
for validation failure and many more options


I then call mInput.Start which dynamically creates a form and adds the 
'fields' to it then displays it for the user to complete along with a OK and 
Cancel button. All very simple and works fine. Each input 'field' is actually 
a usercontrol based on a textbox, checkbox or combobox, which has basic 
validation depending on it's Type (Date, Time, Currency and so on)

I check the result of mInput and if False I discard the inputs and if True I 
process them. Simple

Now I need to step it up a gear. Some 'fields' (remember they are my 
usercontrols) require 'extra validation' not catered for in the basic 
control, for example to check if the input is in a database lookup list. A 
specific example is to check against a database record to see if a customer 
is restriced or not.

My problem is how to perform this 'extra validation' I was hoping I could 
write the 'extra validation' routine then some how (addhandler, addressOf?) 
get the 'field' to use the external routine for validation, returning 
True/False/Reason for failure. The problem is that I need to indicate to the 
'field' what routine to use for the 'extra validation' at runtime, for 
example...

minput.Addfield(Fieldname$="Town",FieldType.Text,Default$="",AddressOf 
ExtraValidation)

Maybe there is another approach.

Thanks for your patience

0
Utf
11/15/2009 1:37:02 PM
Nigel V Thomas schrieb:
> My problem is how to perform this 'extra validation' I was hoping I could 
> write the 'extra validation' routine then some how (addhandler, addressOf?) 
> get the 'field' to use the external routine for validation, returning 
> True/False/Reason for failure. The problem is that I need to indicate to the 
> 'field' what routine to use for the 'extra validation' at runtime, for 
> example...
> 
> minput.Addfield(Fieldname$="Town",FieldType.Text,Default$="",AddressOf 
> ExtraValidation)

With the Call statement (above) and the $ signs, it looked to me like a foreign langauge
at first sight. :-)

What you need is a delegate:

	delegate function MyValidationFunction(input as string) as boolean

mInput class:
	sub AddField(......, ValidationFucntion as MyValidationFunction)

Call:
	minput.AddField(...., addressof ExtraValidation)
	



-- 
Armin


0
Armin
11/15/2009 2:05:50 PM

"Armin Zingler" wrote:

> Nigel V Thomas schrieb:
> > My problem is how to perform this 'extra validation' I was hoping I could 
> > write the 'extra validation' routine then some how (addhandler, addressOf?) 
> > get the 'field' to use the external routine for validation, returning 
> > True/False/Reason for failure. The problem is that I need to indicate to the 
> > 'field' what routine to use for the 'extra validation' at runtime, for 
> > example...
> > 
> > minput.Addfield(Fieldname$="Town",FieldType.Text,Default$="",AddressOf 
> > ExtraValidation)
> 
> With the Call statement (above) and the $ signs, it looked to me like a foreign langauge
> at first sight. :-)
> 
> What you need is a delegate:
> 
> 	delegate function MyValidationFunction(input as string) as boolean
> 
> mInput class:
> 	sub AddField(......, ValidationFucntion as MyValidationFunction)
> 
> Call:
> 	minput.AddField(...., addressof ExtraValidation)
> 	
> 
> 
> 
> -- 
> Armin
> 
> 
> .
> 
Armin

Thanks for the reply. I'm a bit out of my depth with delegates, spent the 
afternoon researching, but still a bit vague.

In your example, how do I get the validation event of my UserControl to call 
the delegate function?

I have a solution using CallByName where I pass the name of the validation 
routine in the Tag of my usercontrol. Are Delegates preferable?

Nigel

0
Utf
11/15/2009 6:09:01 PM
Nigel V Thomas schrieb:
>> What you need is a delegate:
>>
>> 	delegate function MyValidationFunction(input as string) as boolean
>>
>> mInput class:
>> 	sub AddField(......, ValidationFucntion as MyValidationFunction)
>>
>> Call:
>> 	minput.AddField(...., addressof ExtraValidation)
>> 	
> 
> Thanks for the reply. I'm a bit out of my depth with delegates, spent the 
> afternoon researching, but still a bit vague.
> 
> In your example, how do I get the validation event of my UserControl to call 
> the delegate function?

Somewhere you probably store the delegate. If the variable is named "ValidationFucntion"
like the parameter in the AddField method above, you call the method just by typing

	result = ValidationFucntion(value)

> I have a solution using CallByName where I pass the name of the validation 
> routine in the Tag of my usercontrol. Are Delegates preferable?

Yes, absolutely. CallByName uses reflection. This is dangerous as mentioned
before and it is slow. Always have the compiler do as many checks as possible.

-- 
Armin

0
Armin
11/15/2009 7:09:29 PM
Reply:

Similar Artilces:

Help rank features for future Dynamics GP releases
Each year, we ask customers to give us valuable insight into the enhancement of our products. When you give us your feedback and opinions, you help us refine our software to make it even more customer friendly. Please take a few moments to visit the URL below and complete the Product Advisory Board Survey now. This forum is an important way for us to get your opinion on our products, but this special opportunity is available for a limited time. https://mbs.microsoft.com/customersource/pabs -- This posting is provided "AS IS" with no warranties, and confers no rights. We w...

What we mean by Assignment Field ?
Hi , Refer this URL. http://office.microsoft.com/en-us/project/HP453048551033.aspx What we mean by "assignment field" ? Thanks KS ks2008 -- When you apply the Task Usage view, you see the complete list of tasks, plus the the resource assignments for each task. The resource assignments are the names of the resources assigned to each task. In the default Task Usage view, you see the Work column to the right of the Task Name column. This column shows you the total amount of Work for the task, plus the Work for each resource assignment. When you look at the ...

how to add a combo box in to a excel cell using VBA dynamically?
Hi All, I am trying to use a excel grid control and I need to a add a combo box in to a cell dynamically, in an Add-In. Please provide me a VBA sample code which I can use for this. Regards Gamini ...

dynamic picklists
I am attempting to use the sample code from the CRM 3.0 SDK to dynamically set a drop down list. I am getting and error on this line in the code: oTempArray[iIndex] = oSubIndustry.originalPicklistOptions[i]; Can anyone tell me if 'originalPicklistOptions is this really valid for a picklist? ...

Why wouldn't a control event handler be called?
Hello to all, I am using Visual Studio .Net and I want to create a dialog-based appllication using C++. I have a Combo Box at the top of the dialog with 3 items in its drop down list. Each time the user selects an item a different layout of dialog controls will show. It is a sort of Tab Control but instead of having three tabs, in my case, I have the Combo Box to change between different layouts. I did this by creating 3 modeless dialogs in my form view. The problem is that I can't receive the control's event. For example, I have a check box called IDC_BTN_ENABLE. I added its ev...

Private assignment RV
Hello with all, I would wish to pass a large quantity of RV into private. There would be an automatic solution. Thank you in advance. RV? -- Sue Mosher, Outlook MVP Author of Microsoft Outlook Programming - Jumpstart for Administrators, Power Users, and Developers http://www.outlookcode.com/jumpstart.aspx "Kirk" <t@t.t> wrote in message news:%234WGyHuAFHA.2316@TK2MSFTNGP15.phx.gbl... > Hello with all, > > I would wish to pass a large quantity of RV into private. There would be > an automatic solution. > > Thank you in advance. > >...

Microsoft Dynamics CRM 4.0
I've a few issues with CRM 4.0 and I was wondering if you could help me. I created a sample data so you can better understand my needs. "Account Name", "Contact Full Name, Role, Primary Contact, Email "Company 1", "John Smith ", "President", "No", "js@company1.com "Company 1", "Michael Smith", "Director ", "Yes", "mic@company1.com "Company 2", "Wayne Smith", "President", "Yes", "way@company2.com "Company 2", "John Smith &...

event handlers
I've added the following two lines to the message map of an mfc activex control which consists of a dynamically created richedit control. ON_EN_CHANGE(IDR_RICHEDIT, &CSodeXRichTextCtrl::OnEditRichText) ON_NOTIFY(EN_LINK, IDR_RICHEDIT, &CSodeXRichTextCtrl::OnEnLinkRichedit) They work fine for the EN_LINK en CHANGE event. However I would also like to react to a user clicking inside the Richedit Control. I guess I have to react to the WM_COMMAND message. But I can't figure out how. Could someone help please? Nevermind found it, EN_MSGFILTER, one day i'll know them all o...

assign permanent colors to bars/values in a pivot chart
I have a column in my source data called "TIER" so the values are 1, 2, 3 etc. when I convert to a pivot chart I want those values/bars to be automatically & permanently assigned a specific color. Eg. Tier 1 = Green, Tier 2 = Yellow etc. Can you help? The colours in a chart are taken from default settings for the data series in the defined order. You can change these default settings in Tools/Options/Color(tab). You see the 56 standard colours and under the thin line the colours for Chart fills and Chart lines. The first series is the left colour, etc up to 8 colou...

In a 2 Y-Axis chart, how do I assign data ranges to an axis?
I have created a 2 Y-Axis chart with 12 data ranges. Numerically, the first 8 data ranges belong on the 1st Y Axis, and the last 4 data ranges belong on the 2nd Y Axis, but MS is choosing to put the first six on the left Y Axis and the last six on the right Y Axis. I need for the chart to display 8 on the left Y Axis and 4 on the right. Please advise. Thank you I find it best to ignore the "built-in custom" types because they do what they want. The following process works on either the normal or built-in custom types. Double click a series, and on the Axis tab, select prim...

Dynamic Charting #2
Hi everyone, If i have a data such as: Chicago ......Newport.........Bellevue January.........52.............67.................76 February........34 .........57.................98 March...........56.............67................45 April.............67............36..................67 May..............67...........56..................99 and i want to display a chart for each branch seperatly. I know i can display in a column chart the volume sold in all 3 branches with the month diplayed, but i'm trying to create a scollable menu(for example) where i can select the branch and dis...

Sports team assignment
I am trying to determine how to do the following: I need to assign players to teams in a flag football league. The number of teams will depend on the number of players. The skill level of players must be taken into account to insure that teams are all equally talented as best we can. In order to measure skill level, players will be assigned a number from 1-4 with 4 being a very skilled athlete and 1 being a beginning player. Each team should have the same number of players. Can someone help me to do this with excel? Thanks in advance. ...

Help needed to show dynamic images on report
Hi Experts, I have to show some images as logo in my ssrs 2008 report. Logo images are stored in a shared folder with .jpj extension on server. Logo file path and name is comming from the custom assembly used in my report. Everything works fine if all the logo files present on the shared folder. But when the specified file is not present in the shared folder then I my report is showing on red X icon in place of Image. I want to hide this red X icon if the files were not present. I have found one discussion with the same issue at http://thecrmgrid.wordpress.com/2009/03/24/ssrs...

Frx for Dynamics Btrieve/Pervasive will need a registration number
Hi, I am currently covering for the normal manager of information systems. They currently have great plains 7.00g12 and Frx6.5. Everything was working for years, until today. Today, when trying to use Frx, all users are getting the following error: Frx for Dynamics Btrieve/Pervasive will need a serial number in 27 days. The thing is after this screen they can't use the program at all anymore, yet on my machine I do get the error, but at least can use it. I do have an administrative account though, while they don't. So, I went looking through all of the managers files found...

Dynamic Charting But for a Stacked Colum Chart
Hi Excel charting Gurus, I have been trying for 3 days to adapt the dynamic Charting examples from Jon Peltier's and TechTrax (http://pubs.logicalexpressions.com/ Pub0009/LPMArticle.asp?ID=246) But I Need to chart with a Stacked Column where the dates are stacked along the X axis Here is a link to what I am trying to do (www.jonson.ca/2Axis Not Dynamic2.xls) So that I do not have to make 12 charts, I want to allow the user to pick a start and end dates (Via Sliders, That I get no problem!) and have the chart update based on the selection. Basically I want the functionality that is in t...

Assigning values as codes
I would like to ask for help please. How do you assign values and make them as codes in excel? For example, I made a list of validation in excel (a drop-down list). Say that the list includes the gender of a person = male, female. How do I assign a number to the gender like 1 if male and 2 if female? Any help would be appreciated. Thanks If you are happy to use another column: =IF(A2="male",1,2) This aaumes that the validation ensures the enty is either male or female But why do this? If you have entered textual values why convert to numbers. You can summ the occurences of "mal...

Assign leads by percentage
I am working on a query to assign leads by percentage available. So for example if we have: 25 Source A 10 Source B 15 Source C And I want to assign 10 leads by a user, it would take 5 from Source A, 2 from Source B and 3 from Source C. We have many lead sources and I want to take up the least amount of resources when doing this. Should I use several counts, a SQL query?? -- Message posted via AccessMonster.com http://www.accessmonster.com/Uwe/Forums.aspx/access-queries/200710/1 SELECT -int(- [Total Wanted] * Lead / (SELECT SUM(Lead) FROM tableName) ), source FROM tableName where ...

Assignment Usage cube
I am trying to extract earned value data from Project Server 2007's underlying databases. I believe the data can be found in the Assignment Usage cube. In 2003, the cubes were visable in the database. However, in 2007, I am unable to locate cube data. Any suggestions? Thx The only officially supported data you can mine from the databases is the Reporting db which also holds interim data for cube building. The schema for the reporting db is in the SDK. Note that there are some very useful Views included that automatically hold all custom fields. -- Rod Gill Microsoft MV...

Entities dynamic picklist
Hi, Is it possible to use two dynamic picklists as a subtitue to filtered lookup? The values should be loaded dynamically from two ENTITIES. I read: http://ronaldlemmen.blogspot.com/2007/05/dynamic-picklists-and-other-samples.html I also read the MS code for states/Cities But the attributes for the picklists should be records in other CRM tables. The Master/Details is not required to enable the user to add or modify the results, which is done by another user on other occasions, only to filter. I read also the ServerSide code sample for (single) CrmPickListControl in the "Programming CRM...

Import Assignments Using Excel
I've exported the assignments from an existing schedule to Excel, this gives me the proper structure; I've updated the hours leaving everything else unchanged, and tried unsuccessfully to import the data back into MS Project using WBS as the Merge Key. It doesn't work. What am I doing wrong? Thank you. The Excel export/import looks like this: WBS Resource Work 1.2.1 Lead Engrg 10 1.2.2 Sr Engrg 20 1.2.3 Engrg B 30 Hello WorkingMan, I suggest ex...

Add Mfg tables to a Dynamics report in Report Writer
Can anyone tell me how to add tables and fields from a 3rd party dictionary (like Manufacturing) to the regular Dynamics reports? thanks! Doug -- Doug It's not difficult to do this as I've done it before but not specifically in Manufacturing. You can read examples in the CustomerSource/Knowledge Base for Report Writer i.e. "How to add Customer PO Number to the Purchase Order Blank Form", for instance, and try to link the steps how it's done for your own reports. "Doug" wrote: > Can anyone tell me how to add tables and fields from a 3rd party dicti...

Assigning print date / batch number to reports & invoices
Hi, I want to assign a print date to things that are only supposed to be printed once such as invoices, statements, etc. I have a invoice table. On the invoice table, I have PrintDate, which is the date the individual invoice was printed. The query select all invoices with no print date and prints them. I will be changing the PrintDate to the BatchNo field. I'll have a ReportBatch table (keyed by BatchNo) where I will record the date, time, report name, and other information about the different reports that are printed. And my query will be change to select all ...

Random assignments
I am attempting to set up a staff rotation. Lets say I have anywhere from 3 - 8 stations. I would like to randomly assign a name to a station on a daily basis to assure faireness. Example: Monday Bill = 1 Jane = 2 Sue = 3 John = 4 Tuesday Jane = 1 Sue = 2 John = 3 Any advise is most appreciated ...

How do I Assign Macro to a button?
I have a problem in trying to assign a macro to a button in Excel 2002. When I create the button, and then click on the button, the "Assign Macro" command is grayed out (unavailable). I cannot figure out what's wrong. When you click on the button, click on its border. Around the button, you'll see a thick dotted border. (If you click inside the button, you'll see a thick border with diagonal lines, and you won't be able to assign a macro.) Right-click on the button border, and choose Assign Macro. BellExcel wrote: > I have a problem in trying to assign a ...

Bulk Close Campaign Responses as Complete in Microsoft Dynamics CR
I need to close several thousand campaign responses and used the bulk import wizard to create the campaign responses but cannot close the responses in bulk . becuasel the bulk close does not give the option of closing as 'Complete" - this is only available from 'Converst' and then only one-by-one. Any ideas how I can bulk close these responses at Complete? ...