Link to home
Start Free TrialLog in
Avatar of lep1
lep1

asked on

How to Create Instance of Existing Object via Casting

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?
Avatar of Melih SARICA
Melih SARICA
Flag of Türkiye image

what error u got ?
Avatar of lep1
lep1

ASKER

The error is that DataGridView1 is Nothing
ASKER CERTIFIED SOLUTION
Avatar of Melih SARICA
Melih SARICA
Flag of Türkiye image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lep1

ASKER

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?
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.
Avatar of lep1

ASKER

ok, thanks