开发者

Dynamically adding and using types in vb.net

I am making a program which dynamically adds objects, such as a button or a checkbox to a form.

For each instance, a handler is added so a certain function is called for the Click event of each object.

Now, when that handler is called, how can I manipulate t开发者_StackOverflow社区he object that fired off the Click event? The Sender object is useless here as I cannot change the location, text, parent, nothing at all.

Since the objects are being created dynamically, their instance name is unfortunately always going to be the same, therefore I cannot simply do things like button1.Text = "Button 1".

I really do not want to create a new subroutine for every type since the actions that would be performed are the same...so how can I manipulate these objects?

There are, at last count, 27 different object types which are being manipulated, and which I want to be manipulated by a single sub.

Thanks for the help!


It sounds like the sender is what you want, as this will be the object that fired off the Click event. You just need to figure out a way to cast it to the required type.

If you are just manipulating location, text and parent, then casting to Control will be enough:

Dim c As Control = CType(sender, Control)

Otherwise you will need to cast to the specific type which means you will need different routines per type.

Another option is to turn on late binding, which I believe in VB is Option Strict Off. Then you can refer to control properties even without the casting -- .NET will look for the property at runtime (and, be warned, will throw an exception if the property's not there).


Cast the sender to Control & you can do what you want (all your objects are Controls right?)


If you know the type of input that called the handler, then you can use typecasting to solve your issue:

Sub General_OnClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim b As Button = sender
    b.Text = "Hello World!"
End Sub

If you don't, which you don't seem you, you might try casting to Control instead, this may give you enough control, depending on what you need to do. If not, you can always do something like:

Sub General_OnClick(ByVal sender As Object, ByVal e As EventArgs)
    If TypeOf sender Is Button Then
        Dim b As Button = sender
        b.Text = "Hello World!"
    Else If TypeOf sender Is TextBox Then
        Dim tb As TextBox = sender
        tb.Text = "Goodbye cruel world!"
    End If
End Sub

EDIT: Updated to translate into VB.Net

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜