the Values were shared by many forms !

  • Thread starter Thread starter Kylin
  • Start date Start date
K

Kylin

How can I set a values in a mainform,
and all the other's windows form can get this value ?
I have a try,
but failed !
any document ,or some simple code ?
 
There are a few ways to do this.

First you could expose a public property on your main form and access that
property from your second form.

Second you can create a class that has a static (shared = vb.net) variable
in it and set that variable from your main form and access it from your
second form.

There are other ways also but those are the quickest and least amount of
trouble probably.

Let me know if this helps or if you need help implementing either of these
solutions.

-Richard
(e-mail address removed)
 
to solve this ,
I make a simple project,
that include two forms : Form1 ,Form2,
and I drag a TextBox and a Button into Form1,
and the Button's onclick like this :

Form2 form=new Form2();
form.label1.Text=textBox1.Text;
form.Show();

and In form2,
I drag a Label and a Button ,
public System.Windows.Forms.Label label1; //public !
private System.Windows.Forms.Button button1;

and the button's onclick here:
MessageBox.Show(label1.Text);
this is ok !

but if this code is writed in Form2's constructor
public Form2()
{
InitializeComponent();
MessageBox.Show(label1.Text);
}

Failed ! and the messagebox show that : label1
why ?
 
It has to do with these lines of code:

1: Form2 form=new Form2();
2: form.label1.Text=textBox1.Text;
3: form.Show();

1B: public Form2()
2B: {
3B: InitializeComponent();
4B: MessageBox.Show(label1.Text);
5B: }

What you are doing here is
1: You are Initializing the form. This calls the constructor "public form2
()" in form2. This is where you have your messagebox. What is happening
is you are calling your message box to soon. Your second line of code
form.label1.Text=textBox1.Text; hasn't been executed yet. So the label on
form2 has a text value of what it was initialized at which is label1. If
you want your messagebox to show the correct value simply put your message
box in the Form2_Load event.

Let me know if that helps or if I didn't explain it well enough.
-Richard
 
Back
Top