?
Solved

VB.NET - Assign DataGridView control object at runtime

Posted on 2013-11-30
4
Medium Priority
?
1,062 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 63

Expert Comment

by:Fernando Soto
ID: 39687074
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 85
ID: 39688053
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 85

Accepted Solution

by:
Scott McDaniel (Microsoft Access MVP - EE MVE ) earned 0 total points
ID: 39688964
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 85
ID: 39700535
See my comment above
0

Featured Post

Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses

777 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