Passing Variable Value

  • Thread starter Thread starter David Bacon
  • Start date Start date
D

David Bacon

Hi All,
I am new to C#, and am having trouble passing the value of a variable
from one windows form to another.

Can anyone point me in the right direction.

Any help here would be greatly appreciated.

Thanks
David
 
More detail would be good... But I'll use my intuition;

Maybe you have a TextBox on FormA called textBox1 and you want to set the
textof a label on FormB (called label1) to the text of textBox1.

Because FormA.textBox1 is private, FormB can't access it by simply
referencing FormA.textBox1.Text;

If this where the case, you'd might want to create a public property for
textBox1.Text that looks like this;

// class FormA
public string TextOnFormA
{
get
{
return this.textBox1.Text;
}
set
{
this.textBox1.Text = (string)value;
}
}
//

Then FormB could reference (get and set) the text of FormA.textBox1 like
this;

// class FormB
this.label1.Text = FormA.TextOnFormA;
//

Of course you could also just make textBox1 public, but that's not really
the "right way".

Sound close to what you want?
Josh
Microsoft.com Tools
 
Thats Close,
Lets say you have a string "sItemNumber" on form 1 and you want to pass
that same string "sItemNumber" in form 2 to use as part of a SQL command.
 
Thats Close,
Lets say you have a string "sItemNumber" on form 1 and you want to
pass
that same string "sItemNumber" in form 2 to use as part of a SQL command.

Either use a property or a public method in Form 2 that accepts the string
as a parameter.
In both cases you need a reference to Form 2 to be able to access it.
In case of a common "parent" it might be better to call upon the parent to
pass on the string.
If Form 1 is the "parent" of Form 2 (you create Form 2 from within Form 1)
keep the reference to Form 2 for later use

Form2 f2 = new Form2();
f2.TextOnForm2 = "somestring";
f2.CreateSqlString("somestring");

if Form 2 is the parent form, pass 'this' when creating Form 1 and store
the "parent" in Form 1 for later use

Form1 f1 = new Form1(this);

public class Form1
{
Form2 parent = null;

public Form1(Form2 parent)
{
this.parent = parent;
}
}

and then use

parent.TextOnForm2 = "something";
parent.CreateSqlString("somestring");

This assumes Form2 has a property TextOnForm2 or a method CreateSqlString

public string TextOnForm2
{
get{}
set{}
}

public void CreateSqlString(string sourceString)
{
}
 
Back
Top