Home All Groups Group Topic Archive Search About

cast from string to button

Author
13 Jun 2006 9:19 AM
Jon Vaughan
Im trying to make some code that can reference x amount of buttons and then
switch visible to false

For x = 1 To 10

    btnSelected = CType("btnButton" & x.ToString, Button)

    btnSelected.Visible = False

Next

Provides the error :

Value of type 'String' cannot be converted to 'System.Windows.Forms.Button'.

Any ideas, about converting string to object types such as buttons ?

Author
13 Jun 2006 9:51 AM
Cor Ligthert [MVP]
Jon,

If you will add this string on runtime, than the best approach is to add the
values from the string to the Tag of the button. (typed here so watch typos
or whatever)

Than you get

For each ctr in controls
    if typeof ctr Is button then
            if ctr.tag.toString = TheGivenString
                   btnSelected.Visible = False
             end if
     end if
Next


This goes fast, you can do it as well with late binding using reflection but
that will cost you performance.

In development time this kind of instructions are in my opinion without
sense when you know the name of a control than there is no need to use a
string. (It looks than like a misplaced way of using scripting).

I hope this helps,

Cor
Author
13 Jun 2006 12:09 PM
Jon Vaughan
Thanks cor , helped alot

Show quoteHide quote
"Cor Ligthert [MVP]" <notmyfirstn***@planet.nl> wrote in message
news:%23259y6sjGHA.4444@TK2MSFTNGP02.phx.gbl...
> Jon,
>
> If you will add this string on runtime, than the best approach is to add
> the values from the string to the Tag of the button. (typed here so watch
> typos or whatever)
>
> Than you get
>
> For each ctr in controls
>    if typeof ctr Is button then
>            if ctr.tag.toString = TheGivenString
>                   btnSelected.Visible = False
>             end if
>     end if
> Next
>
>
> This goes fast, you can do it as well with late binding using reflection
> but that will cost you performance.
>
> In development time this kind of instructions are in my opinion without
> sense when you know the name of a control than there is no need to use a
> string. (It looks than like a misplaced way of using scripting).
>
> I hope this helps,
>
> Cor
>
Author
13 Jun 2006 1:46 PM
Herfried K. Wagner [MVP]
"Jon Vaughan" <jonnyvaug***@hotmail.com> schrieb:
>    btnSelected = CType("btnButton" & x.ToString, Button)

Accessing controls by their names or indices
<URL:http://dotnet.mvps.org/dotnet/faqs/?id=controlbynameindex&lang=en>

--
M S   Herfried K. Wagner
M V P  <URL:http://dotnet.mvps.org/>
V B   <URL:http://classicvb.org/petition/>