Accessing Form's Controls from another class

EDIT: Lot of edit.

public partial class Form1 : Form
{
    // Static form. Null if no form created yet.
    private static Form1 form = null;

    private delegate void EnableDelegate(bool enable);

    public Form1()
    {
        InitializeComponent();
        form = this;
    }

    // Static method, call the non-static version if the form exist.
    public static void EnableStaticTextBox(bool enable)
    {
        if (form != null)
            form.EnableTextBox(enable);
    }

    private void EnableTextBox(bool enable)
    {
        // If this returns true, it means it was called from an external thread.
        if (InvokeRequired)
        {
            // Create a delegate of this method and let the form run it.
            this.Invoke(new EnableDelegate(EnableTextBox), new object[] { enable });
            return; // Important
        }

        // Set textBox
        textBox1.Enabled = enable;
    }
}

This is just another method:

TextBox t = Application.OpenForms["Form1"].Controls["textBox1"] as TextBox;

You could let your class1 have an event to enable the Textbox.

public class Class1
{
  public event Action<object, EventArgs> subscribe ;
  private void raiseEvent()
  {
     var handler = subscribe ;
     if(handler!=null)
     {
        handler(this,EventArgs.Empty);//Raise the enable event.
     }
  }
}

Let the class containing the TextBox subscribe to it somehow. In TextBox wrapper class

 public class TextBoxWrapper
       public void EnablePropertyNotification(object sender, EventArgs args) 
       {
          TextBox1.Enabled = true ; //Enables textbox when event is raised.
       }
       public TextBoxWrapper()
       {
         class1Instance.subscribe+=EnablePropertyNotification ;
       }

Tags:

C#