Accessing Form's Controls from another class

I have a windows forms application with some controls added to the designer. When i want to change something (LIKE) Enable a text box from inside the Form1.cs

i simply use

textBox1.Enabled = true;

but now i have a separated class called class1.cs

How could i enable textBox1 from a static function class1.cs ?

{NOTE} I did not tried any code because i am totally clueless about doing this.

Answers


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 can pass the instance of your Form to the class

 MyForm frm = new MyForm();

 MyClass c = new MyClass(frm);

Then your class can take that instance and access the textbox

 public class MyClass
 {

   public MyClass(MyForm f)
   {
      f.TextBox1.Enabled = false;
   }
 }

The design does not look OK

It is better to call the class in your form and based on the value returned, manipulate the textbox

//MyForm Class

 MyClass c = new MyClass();
 c.DoSomethings();
 if(c.getResult() == requiredValue)
   textBox1.enabled = true;
 else
   textBox1.enabled = false;

//MyForm Class ends here

UPDATE

public class Class1
{
   public static int SomeFunction()
   {
      int result = 1;
      return result;
   }

   public static void SomeFunction(out int result)
   {
      result = 1;
   }
}

Usage

if(Class1.SomeFunction() == 1)
   textBox1.Enabled = true;
else
   textBox1.Enabled = false;

OR

int result = 0;
Class1.SomeFunction(out result);

if(result == 1)
   textBox1.Enabled = true;
else
   textBox1.Enabled = false;

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 ;
       }

You shouldn't really change UI controls in your Form from your class1, but instead create a method or a property in class1 that would tell if the textbox should be enabled or not.

Example:

// I changed the name class1 to MySettings
public class MySettings
{
    public bool ShouldTextBoxBeEnabled()
    {
        // Do some logic here.
        return true;
    }

    // More generic
    public static bool SetTextBoxState(TextBox textBox)
    {
        // Do some logic here.
        textBox.Enabled = true;
    }

    // Or static property (method if you like)
    public static StaticShouldTextBoxBeEnabled { get { return true; } }
}

Then in your form:

MySettings settings = new MySettings();
textBox1.Enabled = settings.ShouldTextBoxBeEnabled();

// Or static way
textBox1.Enabled = MySettings.StaticShouldTextBoxBeEnabled;

// Or this way you can send in all textboxes you want to do the logic on.
MySettings.SetTextBoxState(textBox1);

I had to do this at work and didn't find that any of these answers matched what I ended up doing, so I'm showing how I made it work.

First, initialize a copy of your class in your load event.

NameOfClass newNameofClass;

Then you want to bind to your class (in the load event):

textBox1.DataBindings.Add(new Binding("Enabled", newNameofClass, "textBox1Enabled"));

In your class, do the following:

private bool textBox1Enabled = false;
public bool TextBox1Enabled
{
    get
        {
            return textBox1Enabled;
        }
        set
        {
            textBox1Enabled = value;
        }
}
  • The false setting will initialize your textbox to being disabled
  • Set textBox1Enabled to true if you want to enable by default.
  • If you have other logic to enable/disable the textbox, simply modify the value of textBox1Enabled accordingly.

This is how you should do : I wrote the code below in my form class :

public static Form1 form = null;

    private delegate void SetImageDelegate(Image image);

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

    public static void SetStaticImage(Image image)
    {
        if (form != null)
            form.pic1.Image = image;
    }

    private void setImage(Image img)
    {
        // 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 SetImageDelegate(setImage), new object[] { img });
            return; // Important
        }

        // Set textBox
        pic1.Image = img;
    }

and the code below should be in anouther class :

Form1 frm= Form1.form;
frm.pic1.Image = image;

Note that i changed private static Form1 form = null; to public static Form1 form = null;

Good Luck ... Written by Hassan Eskandari :)


Need Your Help

remove facebook like button social text

facebook facebook-like social

I would like to remove the social text from the facebook like button in order to fit into the width I have spare left but I can't find how on the facebook developers site

Images not displaying on hosting in IIS

asp.net iis-7

I hosted my website on IIS a few days back and it worked perfectly. I then hosted it on another machine and it stopped displaying the images. I checked online and enabled the static content option in