I have an application in C# .NET which has a MainForm
and a few classes.
One of these classes receives incoming data messages from a network. I need to get these message's text appended into a multi-line textbox on the MainForm
.
I can send the message to a method in the MainForm
by making the method static, but then the static method cannot access the MainForm
's controls.
TheIncomingDataClass.cs
namespace TheApplicationName
{
class TheIncomingDataClass
{
public void IncomingMessage(IncomingMessageType message)
{
TheApplicationName.MainForm.ReceiveMSG(message);
}
MainForm.cs
public static void ReceiveMSG(string message)
{
txtDisplayMessages.AppendText(message); //This line causes compile error
}
The compile error:
An object reference is required for the nonstatic field, method, or property 'TheApplicationName.MainForm.txtDisplayMessages'
To continue the way you've been doing it, your "
TheIncomingDataClass
" should have a reference to theMainForm
object with which it should interface. When you create an instance of this class (presumably from an instance method ofMainForm
), you will need to pass in a reference to thisMainForm
object.However, as suggested by Bugs, you probably would be better off making this an event on
TheIncomingDataClass
and subscribing to it fromMainForm
.You can solve this problem by removing the static keyword.
When you see "static", think: without an instance of this type.
When you call a non-static method, you must explicitly use some instance. The method can access that instance using the "this" keyword.
When you call a static method, there is no instance - you have abandoned the boundaries of OO and are now in a structural or functional programming context. If you want an instance of something, you need to bring it in as a parameter.
I think you might be taking the wrong approach on this. It sounds like you are trying to push messages to a client from an external process. There are ways to do this, but it will get complicated. My suggestion would be to have the client poll whatever process has the data periodically - maybe every 10 seconds depending on your needs. This is going to be a heck of a lot easier than pushing from server to client.
Its possible to pass in a reference to the current form like this:
Although as suggested an event is probably a better way of doing it.