Link to home
Start Free TrialLog in
Avatar of daghoff

asked on

Option Strict On disallows late bindings when calling AddHandler Sub

I have a huge VB.NET application I have just converted to Option Strict On. It creates hundreds of dynamically created controls (Buttons, TextBoxes, ComboBoxes etc.) on several forms. When the user attend these controls (for instance updating the text in a TextBox) I need to execute some code related to that control and it’s current value. My concept is to give the controls name property a value and in the control's AddHandler sub I look in for this value to determine which control was used. This works fine when Option Strict is Off, but when I turn it on I get a “Option Strict On disallows late bindings” compile error in the “” code line. Here is a short example of the code I use:

Dim tbox(50) As TextBox
Private Sub CreateTextBoxes()
  For X = 0 To 50
    tbox(X) = New TextBox
    tbox(X).Location = New Point(2 * X, 50)
    tbox(X).Name = "X"
    AddHandler tbox(X).TextChanged, AddressOf handler_tbox
  Next X
End Sub

Private Sub handler_tbox(ByVal Sender As System.Object, ByVal e As System.EventArgs)
  Dim A As String = Sender.Name
  '< rest of code >
End Sub

In short my question is how do you pass on the identity of a dynamically created control to the called AddHandler sub when Option Strict is On?

Please note that I am using .NET v2.0 to be compatible with as many PC’s as possible.
Avatar of nepaluz
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of daghoff


Thanx for your reply. It works fine and my big problem is solved.

But I do realise this is not far from what I was working on myself. I had been told CType could solve my problem and when I substitute DirectCast with CType it works just as fine. It was me that just couldn't get the syntax right.

But this leads to my next question. Why do you recommend using DirectCast and not CType? From what I read on internet, DirectCast is a not much used variant of CType. Based on my coding concept and needs (which is staying low and not using any of the latest runtime modules) what would be the best choice?
Directcast and CType are what they say on the tin, literally.

try changing

ByVal Sender As System.Object


ByVal Sender As TextBox

and not casting the sender.

What is the best choice? The one that works, PERIOD.