Chris Klepeis
Chris Klepeis

Reputation: 9983

.Net reference forms application variable

I have a public variable "testStr" in my applications main form. I have a tabControl which adds tabs loaded with user controls. How can I reference "testStr" from these user controls? I would imagine its either Application.* or parentForm.* ... but everything I'm trying isnt working, not really sure how to do it and I'm a bit new to .net... in flex builder i would do something like parentApplication.testStr.

Any help would be appreciated... I'm sure its pretty basic and simple to do.

Upvotes: 0

Views: 179

Answers (4)

colithium
colithium

Reputation: 10327

What about storing information like testStr (and anything else that's related) in its own class and sharing a reference to every other class that needs to use it?

So your MainForm will create an instance of this new class and pass a reference to each UserControl as they are created. That way, the UserControls don't need to know anything about MainForm, they just know about the data they work with. It will also make things easier if you ever change the layout of the app. Always assuming the parent one level above or the top level parent is the Form you want is not very change friendly.

Upvotes: 1

Paul Williams
Paul Williams

Reputation: 17020

You could iterate upwards to get the value:

class MyControl : UserControl
{
   public string GetMyStr()
   {
      for (Control c = this.Parent; c != null; c = c.Parent)
      {
         if (c is MyForm)
         {
            return c.testStr; // I recommend using a property instead
         }
      }
      return null;
   }
}

Or, if the value is the same across all instances, declare it as a const, or a static readonly field, or as a normal static field:

  class MyForm
   {
      public static const string TESTSTR = "...";
   }

   class MyControl : UserControl
   {
      public void DoSomething()
      {
         string s = MyForm.TESTSTR;
      }
   }

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

You could save a reference to your form instance in some static variable. For example you could edit Program.cs:

class Program {
     public static MyForm MainForm { get; private set; }
     static void Main() {
         // ...
         Application.Run(MainForm = new MyForm());
         // ...
     }
}

Then, you could reference the testStr with Program.MainForm.testStr.

Upvotes: 1

Steve Gilham
Steve Gilham

Reputation: 11277

If the tab control is directly inside the top level form then

((this.Parent) as MyForm).testStr

Otherwise you might need to keep taking .Parent until you reach the top of the stack, then casting to the form type.

Alternatively

((this.FindForm()) as MyForm).testStr

I hadn't known about that one before...

Upvotes: 0

Related Questions