Trying to access controls on one form from another

mkell1

New member
Joined
Jun 24, 2004
Messages
1
Programming Experience
3-5
I am currently working on a Windows Forms application where I open a second form to enter and save some values to the database. Upon saving the values, I would like to reset the datasource of the grid control on the first form so that it displays the new data that has been entered on the second form. In VB6, it was simply [FormName].[ControlName].[whatever Property you wanted to access]. This does not work in VB.NET. If I create a new instance of the first form from the second form, it does not refresh the currently open form. I tried to create a shared method on the first form that accesses it's own controls, but I get the message "Cannot refer to an instance member of a clas from within a shared method or shared member initializer without an explicit instance of the class". I am not quite sure how I should create an explicit instance of the class to access the values within the controls - perhaps I am thinking too deeply and overcomplicating things.

If anyone can help me out with determining the best way to access/update the values of one open form from within another open form, it would be greatly appreciated!
 

sampoo

Active member
Joined
Jun 12, 2004
Messages
25
Location
Belgium
Programming Experience
3-5
Normally, you can access objects on other forms than the MainForm (I call it this way...) by doing this: (I know this is very annoying, I had a similar experience when I started on VB.NET (I always used VB6))
The reason why you should do that, is because Forms are not longer objects, which can be accessed directly, but have become classes, which you should initiate...

Imagine we have a form called MainForm, and another form called SecondForm. The app starts at MainForm.
Now, what we have to do, is to create a Module (for easy working). In that module you declare the following things:

VB.NET:
 Friend frmMainForm as MainForm
 Friend frmSecondForm as SecondForm

In the MainForm Load event, you put the following code:
VB.NET:
 frmMainForm=Me
 frmSecondForm=New SecondForm


Now you should be able to do this:

VB.NET:
 frmSecondForm.Show

And you can access an object from one form to another by doing this:

VB.NET:
 'From the MainForm 
 frmSecondForm.[ObjectName].Value=something
 
 'From the SecondForm
 frmMainForm.[ObjectName].Value=something



Hope this helps,


Greetz
 
Top Bottom