Solved

VB.NET - Assign DataGridView control object at runtime

Posted on 2013-11-30
4
985 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
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 84
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 84

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 84
ID: 39700535
See my comment above
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to Retrieve data from SQl database into multiple Textboxes VB.net 25 34
Syntax Error 2 42
Allow User To Arrange Columns At Datagridview 3 19
SQL Exceptions 3 35
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

932 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