How to Create Instance of Existing Object via Casting

lep1
lep1 used Ask the Experts™
on
I am creating a DataGridView dynamically at run-time, and cant seem to be able to instantiate it as an object during casting in another (Form1) subroutine, so that I can change row labels.


Here is how I define the DataGridView in the Form1 Load procedure:


Dim DataGridView1 As New DataGridView

Open in new window


Later, in a subroutine, when I want to change the row labels (numrows is the number of rows), I can't get the cast to work correctly because the cast won't allow me to use "As New" -- as follows:

Dim DataGridview1 As DataGridView = CType(Me.Controls("DataGridView1"), DataGridView)
For i = 1 To numrows
        DataGridview1.Columns.Add(i, "V" & i)
Next

Open in new window



What is the correct way instantiate as an object a control that was spawned dynamically?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
what error u got ?

Author

Commented:
The error is that DataGridView1 is Nothing
Commented:
try

me.controls.find("datagridview1")
Fundamentals of JavaScript

Learn the fundamentals of the popular programming language JavaScript so that you can explore the realm of web development.

Author

Commented:
It worked out that the the syntax

Dim DataGridView1 As New DataGridView

does not add the name "DataGridView1" to the control, so therefore it can't be found in Me.Controls().

I had to use:

DataGridView1.Name="DataGridView1" -->which corrected the problem of not finding the control.

Question: is there a difference between

Dim DataGridView1 As DataGridView

and

Dim DataGridView1 As New DataGridView

in terms of the Name property?

Commented:
Dim DataGridview1 As DataGridView = CType(Me.Controls("DataGridView1"), DataGridView)

in this line, ur trying to find a control that is already on the page ? or trying to add a new one ?

I guess ur trying to find a newly created one..

so u ave to set a name, other wise ssytem ll gave a name automaticly.

Author

Commented:
ok, thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial