I have created two forms in VisualBasic.net.
When the user hit a button on the FormB must a message
box open showing data from a textbox on FormA. Both forms
are open at same time.
I have done this by using global variant but how can I do
it by writing a line of code in FormB?
VB6 always created an implicit instance of every form you defined.
However, there is no implicit instance of a form in a .NET application.
In order for an instance of formB to interact with an instance of formA,
it must explicitly be given to that form.
The first way to do this is by making an explicit instance of each form
in a global location such as you have done
The second way is to have an internal variable in formB to a formA
instance. Then you need to tell the formB instance which formA instance
to store in it's internal variable. This could be done either by
requiring a formA instance in the formB constructor, or by having a
method taking a formA type, or a property of type formA.
An application always needs an entrance point. This is why there is a
"Main" method created in the initial form of a windows forms application.
This is what it looks like in C# (similar to VB.NET, but i don;t have
VB.NET)
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
I usually remove this from the form class and create a new class called
"Startup" or something similar and move the Main method there...
public class Startup
{
static void Main(){...}
}
In this class any variable you want to be "global" just define it as
"static" in this Startup class. Technically you could declare a static
variable anywhere in your application and it behaves like a global
variable. However, it makes it easy to manage your globals if they are
all in one place. Note: VB has a different keyword for "static", and I'm
not sure what it is. Maybe someone else can tell you that?
public class Startup
{
public static formA MyFormAInstance;
...
}
<or>
public class Startup
{
private static formA myFormA;
public static formA MyFormA
{
get{return myFormA;}
}
static void Main()
{ //instantiate globals at application start
myFormA = new formA();
}
}
Now to use this from anywhere else in your application, such as formB...
public class formB
{
public void MyMethod()
{
MessageBox.Show("Form A's textbox value = "
+ Startup.MyFormA.TextBox1.Text);
}
}
Let me know if you want an example of requiring a formA instance in the
formB constructor, or one of the other ways I mentioned.
Michael Lang
All code was typed on the fly. No warranties...