Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one access a control from a static method?

Tags:

c#

.net

winforms

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'

like image 352
timmyg Avatar asked Jun 04 '09 17:06

timmyg


1 Answers

A static method doesn't have access to members like txtDisplayMessages because it is not a part of that instance. I suggest you do some reading on the concepts of static methods and whatnot, because that is a fairly language agnostic concept. That method would best be served by removing the static modifier, because it doesn't need to be static - it appears that it would need to be called by that particular instance of that object.

like image 112
Annath Avatar answered Sep 22 '22 17:09

Annath