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
Solved

VB.NET - Assign DataGridView control object at runtime

Posted on 2013-11-30
4
1,013 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 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 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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
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:…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

856 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