Ian
Ian

Reputation: 1

How do I modify a form's text box from a separate class?

I am trying to create a form where I can update text in a text box without requiring interaction from the user. Right now I am trying to create a method in my form's class that updates the TextBox.Text field. Outside of the class I am not able to access the function.

Right now I am trying

static void Main()
{
    Form status = new Window();
    Application.Run(status);
    status.UpdateTextBox("NewText");
}

My form class looks like (from the designer)

public partial class Window : Form
{
    public Window()
    {
        InitializeComponent(); 
    }

    public void UpdateTextBox(string text)
    {
        textBox1.Text = text;
    }  
}

I have also tried making the Textbox a public property like this.

public string DisplayedText
{
    get
    {
        return textbox1.Text;
    }
    set
    {
        textbox1.Text = value;
    }
}

I am trying to edit the field during runtime. Is this possible?

Upvotes: 0

Views: 280

Answers (2)

µBio
µBio

Reputation: 10758

It's this code...the Application.Run will block, status.UpdateTextBox isn't going to execute until you close the form.

static void Main()
{
    Form status = new Window();
    Application.Run(status);
    status.UpdateTextBox("NewText");
}

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564841

You can access the function, but if you look at the code, there is a problem:

static void Main() 
{
    Form status = new Window(); 
    Application.Run(status);  // Blocks here!
    status.UpdateTextBox("NewText"); 
}

When you call Application.Run(), it will not return control to your program until the status form has closed. At that point, setting the status is too late...

You can set it before you run, but after you've constructed:

static void Main() 
{
    Form status = new Window(); 
    status.UpdateTextBox("NewText"); 
    Application.Run(status); 
}

Upvotes: 1

Related Questions