views:

68

answers:

4

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.

A: 

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...

Steve Gilham
+1  A: 

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.

Mehrdad Afshari
A: 

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;
      }
   }
Paul Williams
+1  A: 

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.

colithium