Results 1 to 25 of 25

Thread: Convert String to Control

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2002
    Location
    Fox, OK
    Posts
    381

    Convert String to Control

    Is it possible to convert a string into a control?
    Dim Ctrl as string = "DataGridView"
    Dim Index as integer = "1"
    Dim g as DataGridView = DirectCast(Ctrl & Index, DataGridView)

    and then access the properties of the Grid...
    g.BackColor = Color.Red
    g.Left = 3
    etc.

    I'm pretty sure it's possible but nothing I've tried works.

  2. #2
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: Convert String to Control

    Not convert it, but you can specify the get the control from the containers collection by its name:
    vb Code:
    1. Dim g As DataGridView = DirectCast(Me.Controls("DataGridView1"), DataGridView)

    But if you really think you need to use this method, you will need to redesign your code.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  3. #3
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Convert String to Control

    you can do it by accessing the control by name from the forms controls collection like this:

    Code:
            Dim Ctrl As String = "DataGridView"
            Dim Index As Integer = 1
            Dim g As DataGridView = DirectCast(Me.Controls(Ctrl & Index.ToString), DataGridView)
    note that the forms controls collection only holds controls directly on the form, so if the DGV is in a panel or another container control like that, you need to use the controls collection of that container, and not the form.

  4. #4

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2002
    Location
    Fox, OK
    Posts
    381

    Re: Convert String to Control

    I suppose that if the control was inside a container on the form (like in a TabControl) that would affect the code wouldn't it?

  5. #5
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Convert String to Control

    yes instead of the keyword Me (which indicates the form) you would use the variable name for the TabPage (not the TabControl) that the given datagridview is on.

    Code:
    Dim g As DataGridView = DirectCast(TabPage1.Controls(Ctrl & Index.ToString), DataGridView)

  6. #6
    New Member
    Join Date
    Dec 2010
    Location
    China
    Posts
    4

    Re: Convert String to Control

    thanks you so much, this info. is good for me.

  7. #7
    New Member
    Join Date
    Jun 2012
    Posts
    1

    Re: Convert String to Control

    I found a shortcut! and its superly duperly dynamic!

    Dim s As String = "textbox"
    Dim c As Object

    If s = "textbox" Then
    c = New TextBox
    c.Text = "This is a textbox"
    c.Location = New System.Drawing.Point(200, 50)
    c.Size() = New System.Drawing.Size(70, 20)

    Me.Controls.Add(c)
    End If

  8. #8
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Convert String to Control

    Quote Originally Posted by iexpress View Post
    I found a shortcut! and its superly duperly dynamic!

    Dim s As String = "textbox"
    Dim c As Object

    If s = "textbox" Then
    c = New TextBox
    c.Text = "This is a textbox"
    c.Location = New System.Drawing.Point(200, 50)
    c.Size() = New System.Drawing.Size(70, 20)

    Me.Controls.Add(c)
    End If
    you misunderstood this thread

  9. #9
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    9,017

    Re: Convert String to Control

    If you want to create a class via a string that represents its type name you can use this:-
    vbnet Code:
    1. '
    2.     Public Function CreateClass(ByVal className As String) As Object
    3.  
    4.         Dim asms() As Assembly = AppDomain.CurrentDomain.GetAssemblies
    5.  
    6.         For Each Asm As Assembly In asms
    7.             Dim types = Asm.GetTypes
    8.  
    9.             For Each T As Type In types
    10.                 If T.Name.Equals(className, StringComparison.OrdinalIgnoreCase) Then
    11.                     Return Activator.CreateInstance(T)
    12.                 End If
    13.             Next
    14.  
    15.         Next
    16.  
    17.         Throw New Exception("Type not found")
    18.     End Function

    Here is a version using Linq:-
    vbnet Code:
    1. '
    2.     Public Function CreateClass(ByVal className As String) As Object
    3.         Dim asms() As Assembly = AppDomain.CurrentDomain.GetAssemblies
    4.  
    5.         Dim typeSought() As Type = (From Asm In asms _
    6.                                 Let types As Type() = Asm.GetTypes _
    7.                                 Let found As Type = Array.Find(Of Type)(types, Function(t) t.Name.Equals(className, StringComparison.OrdinalIgnoreCase)) _
    8.                                 Where found IsNot Nothing Select found).ToArray
    9.  
    10.         If typeSought.Length > 0 Then
    11.             Return Activator.CreateInstance(typeSought(0))
    12.         End If
    13.  
    14.         Throw New Exception("Type not found")
    15.     End Function

    Use it like:-
    vbnet Code:
    1. '
    2.         Dim tb As TextBox = CreateClass("textbox")
    3.         Dim dg As DataGridView = CreateClass("datagridview")
    4.  
    5.  
    6.         Me.Controls.Add(tb)
    7.         Me.Controls.Add(dg)
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  10. #10
    Junior Member
    Join Date
    Jun 2012
    Location
    Colchester, England, U.K.
    Posts
    19

    Question Re: Convert String to Control

    I've read this with interest but still can't get what I want to do to work.
    My requirement is...
    Get a string from a database say dbstr which = "cmd2"
    Create a new instance of a form and then Performclick on the control button named btn2 on that form.
    I'm struggling with the Directcast statement to do this. I've tried
    Code:
    Dim dbstr As String
    Dim btn As New Button
    Dim ssga As New sggAcs //(sggAcs is a project form)
    dbstr = "cmd2"
    btn = DirectCast(ssga.Controls(dbstr), Button)
    If I then try
    Code:
    ssga.btn.PerformClick()
    vb tells me that btn is not a member of sggAcs
    I use this method a fair bit to change the screen colours etc. depending on what the user is doing so any pointers to my errors would be much appreciated.

  11. #11
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: Convert String to Control

    is the button in any sort of container control, like a panel or groupbox?

  12. #12
    Junior Member
    Join Date
    Jun 2012
    Location
    Colchester, England, U.K.
    Posts
    19

    Re: Convert String to Control

    Yes it's in a panel.
    does that mean I should have put
    ssga.panelname.btn.PerformClick()
    I'll go and try it.
    Thanks.

  13. #13
    Junior Member
    Join Date
    Jun 2012
    Location
    Colchester, England, U.K.
    Posts
    19

    Re: Convert String to Control

    Panel is called pnl2 so I tried this
    Code:
    Dim dbstr As String
    Dim btn As New Button
    Dim ssga As New sggAcs
    dbstr = "cmd2"
    btn = DirectCast(ssga.Controls(dbstr), Button)
    MsgBox(ssga.pnl2.btn.text)
    blue squiggly line under ssga.pnl2.btn - Error List gives "btn is not a member of System.Windows.Forms.Panel"
    Bother!

    i've now tried this - code is in a button_click event on main form.

    Code:
    Dim dbstr As String
    Dim ssga As New sggAcs
    dbstr = "cmd2"
    Me.Text = ssga.pnl2.Controls(dbstr).Text
    when I click the button in main form the title bar changes to the text of the button in the form sggAcs, so I can access the text property of a control on another form without using directcast BUT when I try this which is what I really want to do...
    Code:
    ssga.pnl2.Controls(dbstr).performclick()
    I get an error message - performclick is not a member of 'System.Windows.Forms.Control'
    I'm obviously missing something important here but can't figure out what.
    Any pointers much appreciated.
    Last edited by timjohn; Jul 18th, 2012 at 05:39 PM.

  14. #14
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Convert String to Control

    vb Code:
    1. directcast(ssga.pnl2.Controls(dbstr), Button).performclick()

  15. #15
    Junior Member
    Join Date
    Jun 2012
    Location
    Colchester, England, U.K.
    Posts
    19

    Re: Convert String to Control

    Hi,
    Tried that and as soon as I clicked the button on the main form I got this in the immediate window..
    A first chance exception of type 'System.NullReferenceException' occurred in Gtacs.exe
    Odd as your line of code didn't produce any errors and I don't understand the .exe bit as I'm running in vb2010 debug mode. However Gtacs is the project name, just not compiled yet.

  16. #16
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Convert String to Control

    at the time you got that error, had you created the dbstr button?

  17. #17
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Convert String to Control

    i need to see all of your relevant code.
    i'm not sure if you're adding a button in code or it already exists, + you're trying to refer to it by a string

  18. #18
    Junior Member
    Join Date
    Jun 2012
    Location
    Colchester, England, U.K.
    Posts
    19

    Re: Convert String to Control

    Hi Paul,
    Was in middle of writing to you when you asked for code, so scrapped last post and send this in it's place. Hope it's what you need.
    Here is the code in the main form.
    Code:
    Bit at top of form is this.
    Option Strict Off
    Option Explicit On
    Imports VB = Microsoft.VisualBasic
    Then the relevant button is this.
    Private Sub cmd2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd2.Click
        Dim dbstr As String
        Dim ssga As New sggAcs
        dbstr = "cmd3"
        DirectCast(ssga.Controls(dbstr), Button).PerformClick()
    End Sub
    This is the code for the other form where the buton to be clicked is..
    Code:
    Friend Class sggAcs
        Inherits System.Windows.Forms.Form
        Private Sub cmd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd1.Click, cmd2.Click, cmd3.Click
            If sender.Tag <> gtType Then
                gtType = sender.tag
                gtCode = Trim(gtID) & sender.tag
                If sender.tag = "g" Then
                    gtHead = "General"
                ElseIf sender.tag = "c" Then
                    gtHead = gtCamp
                Else
                    gtHead = "Fundraising"
                End If
                MainGtacs.Text = "Gtracs - " & gtHead & " Accounts - " & gtIdent
                Me.Dispose()
            Else
                Me.Dispose()
            End If
        End Sub
    End Class.
    There is more to go in but it's not there yet.
    BTW, I'm trying to convert(re-writing) a system from VB6. Then I just used the index of an array, not in vb2010 though!

  19. #19
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Convert String to Control

    ok. it seems you're creating + referring to a new instance of your form, instead of the open instance you should be referring to. here's an example using a form (Form2) + a button (Button1):

    vb Code:
    1. DirectCast(My.Application.OpenForms("Form2").Controls("Button1"), Button).PerformClick()

  20. #20
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Convert String to Control

    BTW... you can use an array of buttons in vb.net, but in a different way to the vb6 control array:

    vb Code:
    1. Public Class Form1
    2.  
    3.     Dim btns() As Button
    4.  
    5.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    6.         btns = New Button() {Button1, Button2, Button3}
    7.     End Sub
    8.  
    9. End Class

  21. #21
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Convert String to Control

    are you intending to open a new form + click cmd3?

    why not just use [formName].[buttonName].PerformClick() ?

  22. #22
    Junior Member
    Join Date
    Jun 2012
    Location
    Colchester, England, U.K.
    Posts
    19

    Re: Convert String to Control

    Hi Paul,
    Working backwards
    (21) I only have the button name in a string variable so [formName].[buttonName].PerformClick() doesn't work when I replace [buttonName] with a variable, get the error 'dbstr' is not a member of 'Gtacs.sggAcs'.
    (20) Thanks for that I'll have a play and see.
    (19) I get an error 'OpenForms' is not a member of 'Gtacs.My.MyApplication'

    Sorry to be causing all this, I really thought I was asking something simple (well it was in VB6)- click a control button on a second form & carry out the code on the button click, with the user never seeing the second form. All it took was 3 lines
    Code:
    Load sggAcs
    sggAcs.Command3(gtAcNo).Value = True
    Unload sggAcs
    where gtAcNo was an integer.

  23. #23
    Junior Member
    Join Date
    Jun 2012
    Location
    Colchester, England, U.K.
    Posts
    19

    Re: Convert String to Control

    Think I've got it - not sure if it's the correct way/good coding but it seems to work.

    Add
    Code:
    Public Shared btns() As Button
    to the Target Form below Inherits statement.

    Then Add
    Code:
    btns = New Button() {cmd1, cmd2, cmd3}
    to the Target Forms Load event.

    Then use
    Code:
    Dim dbstr As Integer
    sggAcs.Show()
    dbstr = 2 // dbstr will be filled from the database(-1) & it becomes index of btns.
    DirectCast(sggAcs.btns(dbstr), Button).PerformClick()
    in the calling form.
    If you know a better way I'd appreciate it.

    Thanks are due for all your help in pointing me in the right direction.

  24. #24
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,424

    Re: Convert String to Control

    no need to cast:

    vb Code:
    1. sggAcs.btns(dbstr).PerformClick()

  25. #25
    Junior Member
    Join Date
    Jun 2012
    Location
    Colchester, England, U.K.
    Posts
    19

    Re: Convert String to Control

    Got it, thanks Paul, won't have such a late night tonight.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width