Solved

VB.NET - Assign DataGridView control object at runtime

Posted on 2013-11-30
4
952 Views
Last Modified: 2013-12-06
In VB.NET, I have a form with 3 DataGridView controls. The routine used to fill them does quite a bit of work, and I thought to use a single routine for all of them, and simply make the name of my DataGridView variable to be dynamic:

For each dtr As Datarow in MyDataTable.Rows
  '/ bunch of code here to format data and such
  Dim dg As DataGridView
  dg = Controls("dg" & dtr("Category"))
  '/ more code to format the datagrid
Next

However, the dg variable always resolves to Nothing. The name of the control is correct - for example, dtr("Category") contains a value of "Park", and I have a DataGridView control named "dgPark". I've tried using this:

Dim dg As New DataGridView

With the same results ...

How can I do this at runtime? I have only 3 now, and I can hardcode it, but it seems the code above should work.
0
Comment
  • 3
4 Comments
 
LVL 62

Expert Comment

by:Fernando Soto
Comment Utility
You state this, The routine used to fill them does quite a bit of work, and I thought to use a single routine for all of them, and simply make the name of my DataGridView variable to be dynamic:", can you post the complete function for the new routine.
0
 
LVL 84
Comment Utility
The rest of the code retrieves values from a SQL ServerCE database, so I don't think it'll help, but here it is:

 Function LoadCats()

        dt = New DataTable

        Using cmd As New SqlCeCommand("SELECT * FROM Category WHERE Main_Category=1", GetCon_CE)
            Using rdr As SqlCeDataReader = cmd.ExecuteReader
                dt.Load(rdr)
            End Using
        End Using

        For Each dtr As DataRow In dt.Rows
            Dim cCat As New cCategory
            cCat.Load(dtr("ID"))

            Dim dtCat As New DataTable
            dtCat = CreateBlindTableDataset()

            Dim dg As DataGridView

            Using cmd As New SqlCeCommand("SELECT * FROM Tables WHERE Category_ID=" & dtr("ID"), GetCon_CE)
                Using rdr As SqlCeDataReader = cmd.ExecuteResultSet(ResultSetOptions.Scrollable)
                    If rdr.HasRows Then
                        Do While rdr.Read
                            Dim dtrC = dtCats.NewRow

                            dtrC("Table Number") = rdr("Table_Number")
                            dtrC("Entries") = rdr("Num_Entries")

                            dtCats.Rows.Add(dtrC)
                        Loop
                    End If
                End Using

                dg = Me.Controls("dg" & dtr("Category"))

                Dim txb As New DataGridViewTextBoxColumn
                txb.DataPropertyName = "Table Number"
                txb.Name = "Table Number"
                txb.ReadOnly = True
                dg.Columns.Add(txb)

                Dim ud As New DataGridViewComboBoxColumn
                ud.DataPropertyName = "Entries"
                ud.FlatStyle = FlatStyle.Flat
                ud.Name = "Entries"
                For i As Integer = 1 To 6
                    ud.Items.Add(CStr(i))
                Next

                dg.Columns.Add(ud)

                dg.AutoGenerateColumns = False
                dg.DataSource = dtCats
                dg.RowHeadersVisible = False
                dg.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
            End Using
        Next
        
    End Function

Open in new window

If I step through the code, line 34 executes, but ends up with a value of Nothing, so when the code hits line 40 it bombs.

So, to restate: How can I dynamically set the name of a control?
0
 
LVL 84

Accepted Solution

by:
Scott McDaniel (Microsoft Access MVP - EE MVE ) earned 0 total points
Comment Utility
My DataGridViews were housed in Group boxes on Tab pages, so they were not "top level" controls, and I couldn't get a handle on them using the methods I tried originally.

I ended up using the Find method of the Controls collection, which includes an argument to search the "children" of all controls:

Dim dgs() As Control
dgs = Me.Controls.Find("dg" & dtr("Category"), True)
Dim dg As DataGridView

If dgs.Length > 0 Then
  dg = DirectCast(dgs(0), DataGridView)
  <other stuff here
End If

That worked, and I was able to return a handle to my DataGridView.

Thanks for your efforts, I really appreciate you taking the time to look.
0
 
LVL 84

Author Closing Comment

by:Scott McDaniel (Microsoft Access MVP - EE MVE )
Comment Utility
See my comment above
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now