Friday, December 7, 2007

Accessing Controls !

You might have had some problem in the past in accessing the controls on the Main form, where you want to set properties of controls on your Main form if you are thinking to instantiate the object of Main class and then setting properties of controls then you are thinking wrong because by following this way you are actually creating a new instance of the form and not accessing the instance which is already in Memory. So, in order to solve this problem the following trick will do the work for you.

In your form2 declare a Class level variable of form type e.g.

Dim oForm as Form

now in the Load event of form2 just make this equal to the 'ActiveForm' property of 'Form1' e.g.

oForm = Form1.ActiveForm

Now just enter the following code in the Button Click event handler or in whatever event you want to use in order to add items to the Listbox or whatever you want to do with the control on the form e.g.

Private Sub btnOK_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnOK.Click

CType(oForm, Form1).ListBox1.Items.Add(Me.TextBox1.Text)
'Like this you can now access any control on the Form
'Who's instance is already in memory.

End Sub

I hope this will help you !

No comments: