开发者

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
    {
        tex开发者_开发知识库tbox1.Text = value;
    }
}

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


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


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");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜