In C#, pass values between 2 forms and one Global.cs

J

Jason Huang

Hi,

In Global.cs, I have public string myString="".
Another 2 forms are Form1.cs, Form2.cs.
How do I use the Global.cs' myString to store a string in Form1 and then
pass to Form2?
Thanks for help.

Jason
 
G

Guest

Hi Jason,
I would add a property to Form2 which allows you to pass in a string i.e.

class Form2 : Form
{
private string _thePassedInString;

public string NewFormString
{
set
{
_thePassedInString = value;
}
}

}


so now you would be able to say something like
Form2 f = new Form2();
f.NewFormString = "abcd";

If you want to store data from one place i.e. Form1 and pass it to Form2 at
a later point in time when Form1 is no longer available then I would create a
DataStore object, which is a singleton so you only ever have one instance,
like:

class GlobalDataStore
{
private static GlobalDataStore _instance = new GlobalDataStore();
private string _formString = "";

static GlobalDataStore()
{
}

public static GlobalDataStore GetInstance()
{
return _instance;
}

public string FormString
{
get
{
return _formString;
}
set
{
_formString = value;
}
}
}

Now you can use this object to store and retrieve your data from anywhere i.e.

//Inside Form1
GlobalDataStore.GetInstance().FormString = "abcd";


//Inside Form2
string myStringValue = GlobalDataStore.Getnstance().FormString;


Hope that helps
Mark R Dawson
 
C

Charlieee

Jason,

I'm assuming that Form1 and Form2 are separate classes and can't "see" each
other??? If you try to connect the two, you get a cyclical error?

If so, I have two things to think about:

1. If the forms provide similar tasks, you could create a base class to hold
the "global" or common items and then inherit each form from the baseform.
This would make the myString field automatically visible to both forms and
all others derived from baseform. (As long as myString is public or
protected.)

2. If it doesn't make sense to have a base class, you could use a delegate
in Global that fires off a method in Form2.cs that sets contents of
Global.myString to Form2.myString. The delegate method would be assigned by
Form2 when Form2 is created. Form1 would set Global.myString, then Form1
would call/invoke the delegate, which assignes Global.myString to
Form2.myString (because the method running is really
Form2.myStringFetchMethod.) Sounds a little complicated but it is really
pretty easy to do.

I prefer the base class technique when possible but delegation works great
too.

If you need some code examples, let me know and I'll work one up for you.

Charlie
:)
 

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