Easy C# Question

Status
Not open for further replies.
I'm trying to port some code from a simple command line app to a Windows Based app. I'm having a small problem. I'm trying to get messages to go to a textbox instead of the command line. The code previously used a statement like this
Code:
Console.WriteLine = ("Error trying to get local address {0}" + ex.Message);

How can I get this to a textbox? I've tried the following but it doesn't work.
Code:
textBox1.Text = ("Error trying to get local address {0}" + ex.Message);

Can someone clue me in?

Thanks
 
Code:
textBox1.Text = "Error trying to get local address " + ex.Message;
assuming that Message is a string or has some adequate string
representation.
or
Code:
textBox1.Text = string.Format("Error trying to get local address {0}", ex.Message);
will work,

also, the Console code you posted, seems to have incorrect syntax,
it should be either
Code:
Console.WriteLine("Error trying to get local address {0}", ex.Message);
or
Code:
Console.WriteLine ("Error trying to get local address " + ex.Message);

see the docs of string.Format() and Console.WriteLine()
 

Handor

Ars Tribunus Militum
2,513
ChatServer.Form1 is the name of the namespace and class, I'll bet. If you're designing from within VS.Net then the namespace is the name of your project, and the name of your form is the class name, not the name of an instance of your class. Therefore when you say ChatServer.Form1 you're referring to a class, not an object. The difference is that one refers to information in common between all possible instances of Form1 (and yes, you can have as many as you want), whereas in object references you are accessing both the stuff that's in common and the stuff that's particular to that instance.

In C#, the way you refer to stuff that is held in common between all the instances of your form is to use the 'static' modifier on the member. Since your textbox is a non-static member, you need an object, not a class, to refer to it.

So all you need to do is use an object reference to the form you're talking about. If you're within Form1 (and the method you're in isn't static) just call this.textBox1. In fact, you can probably get away with just referring to textBox1 all by itself.

If you are somewhere other than Form1 when you want to access the text box, you'll need to somehow get an object reference. Easiest way to do that is to pass 'this' (from within Form1) to any method that needs to access it.
 
Status
Not open for further replies.