Reference Control via class

G

Guest

Hello all,
I have, what i think, is a simple question.

On my main form, i have a tabcontrol that contains 10 tabs. In my class, I'd
like to be able to reference the form so i can set properties on the tab
control.

How do i do this?
Thanks in advance.

Richard M.
 
M

Morten Wennevik

Hi Richard,

You need to pass a reference to your form, or the tabcontrol, to your class.
This is typically done in the class consctructor.

// In your form
MyClass mc = new MyClass(this);
....
// And in MyClass
private MyForm parent;
public MyClass(MyForm mf)
{
parent = mf;
}

Now, you need to expose properties or methods (public/protected) in your form that your class can use to read/write to the tabs.
 
M

Morten Wennevik

It looks like you have Form1 where it should be Form2 somewhere.

To repeat the steps in a slightly different way ...

namespace WindowsApplication1
{
// Form1
public class Form1 : Form
{
// TabControl is public for simplicity, in real life you should
// expose it through properties and methods
public TabControl tb;

public Form1()
{
tb = new TabControl();
this.Controls.Add(tb);
}

private void SomeMethodInForm1()
{
// 'this' (Me in VB) refers to the current class, Form1
Form2 f = new Form2(this);
f.ShowDialog();
}
}



// Form2
public class Form2 : Form
{
// Note Form1, not Form2
private Form1 myParent;

public Form2(Form1 f)
{
// f is a reference to a Form1 object ('this' when we created Form2)
// store the reference for later use as we need it to call anything inside Form1
myParent = f;
}

private SomeMethodInForm2()
{
// this will add a TabPage to the TabControl in Form1
myParent.tb.TabPages.Add(new TabPage("Hello"));
}
}
}




Thanks Morten for the quick reply. The problem is though, i don't know
anything about C# and i'm new to VB.NET.

I've been trying to figure out this code located here:
http://msdn.microsoft.com/library/d...ltipleFormsInVisualBasicNETUpgradingToNET.asp

But i keep on getting the following error:
Value of type 'WindowsApplication1.Form2' cannot be converted to
'WindowsApplication1.Form1'.

Please, anyone, HELP!!
Thanks.
Richard M.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top