开发者

C# - Writing to a multiline textbox

I'm trying to write the status of the program to the user. But my method to do so doesn't work. statusBox is a textbox windows form.

   public static void writetoSta开发者_JS百科tus(string text)
        {
            TextBox statusBox = new TextBox(); 
            statusBox.Text = text;
        }

Help please!


You can't access instance variables with a static method. I can't think of a way that statusBox would not be an instance member. Try making your method non-static and it should be fine.


As mentioned in a previous answer, your method needs to be static in order to access the TextBox on your form.

Also pressing, however is the fact that you're putting the status in a new TextBox instead of the one on your form.

If you created a form and put a TextBox on it, then the TextBox already has a name, and you can access it from the code-behind file. By default, I think it would be Textbox1 or some other number. You can, of course, change this name in the designer file or in the form editor GUI in Visual Studio.

So, lets say you change the name of the existing TextBox to statusBox. Now your method need only be this:

void WriteToStatus(string status)
{
    statusBox.Text = status;
}


Ok, i see that you are creating a new instance of text box inside static method. That instance of textbox ends up nowhere and it's destroyed once you your static method is executed.

You can either have:

    public static void writetoStatus(TextBox tb, string text)
    {
        tb.Text = text;
    }

    // and then later use it like: 
    writetoStatus(statusBox, text);

Or:

    public static void writetoStatus(Form frm, string text)
    {
        TextBox tb = new TextBox();
        tb.Text = text;
        frm.Controls.Add(tb);
    }

    // and then later use it like: 
    writetoStatus(myForm, text);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜