BeginnerQ: Handling Global variables in multiform app

cheezy

Member
Joined
Apr 11, 2003
Messages
13
Location
Tulsa, Oklahoma
First App; basic question.

Im developing a test app to see how things work. I have two forms, A and B, and I want a string Astring to be available to both forms, even if the first is closed. I have the following (im leaving stuff out; if you need more info, im here ;) ):
C#:
namespace Doug
{
public class Globals
	{
		public string Astring = "Joe";
	}
public class A : System.Windows.Forms.Form
	{
	private System.Windows.Forms.Button Next_button;
	private System.Windows.Forms.Label label_Regno;
	private System.Windows.Forms.TextBox text_Regno;
	private System.Windows.Forms.Label label1;
  
	 public A()
		{			 
                                 InitializeComponent();
		}
	static void Main() 
		{
		Globals Joe = new Globals();
		A Form_A = new A();
		Form_A.label1.Text = Joe.Astring;
		Form_A.Show();
		Application.Run();
		}

		private void Next_Button_Click(object sender, System.EventArgs e)
		{
	
		B Form_B = new B();
		Form_B.Show();
		this.Dispose();
		}
***** End of stuff in the first .cs file.
*****Begin .cs file that has Form B stuff
C#:
	public class B: System.Windows.Forms.Form
	{
                  private System.Windows.Forms.Label label5;
	private void B_Load(object sender, System.EventArgs e)
		{
			label5.Text = Joe.Astring;
		}
**** End of Form B .cs stuff

Problem is when I go to Debug this stuff I get "namespace Joe could not be found. " Obviously the instance of Globals called Joe I instantiated in the first part isnt available. Does anybody know the error of my ways here?

Thanks.
 
Last edited by a moderator:
I tried label5.Text = Globals.Astring; got the error:

(420): An object reference is required for the nonstatic field, method, or property Doug.Globals.Astring

This would have worked if the original definition for Astring in the Globals class were static. If this was the case (and Ive tried it) I dont even have to create an instance of the Globals class (called Joe; an unfortunate and confusing naming convention for this example; sorry).

Guess the problem is that Ive created an instance of an object called Joe that has an Astring string field which I cant access.

Is it a scope or permissions issue??

Thanks.
 
Change the Astring declaration to make it static:

C#:
public class Globals {
    public static string Astring = "Joe";
}

Then access it from your forms like so:
C#:
label5.Text = Globals.Astring;
 
OK, that fixed the current problem; thanks. But theres a related problem with accessing objects created in one class from another class; it should work but doesnt. Ill open a new thread to keep things simpler.

Thanks again!.
 
Back
Top