c0nfus3d
c0nfus3d

Reputation: 1440

Change a form label text value when setting a static int

I'm trying to change a form label's text value (frmWebInput.ConnectedUserCount.Text) when changing a static int value from another static void...

Basically: It's a simple web server, and I'm trying to keep track of the connected users when each page is served. It seems to be working, but the form label is not getting changed though?

/**
 * @type int Total connected users.
 */
 private static int _connectedUsers = 0;
 public static int connectedUsers {
     get { return _connectedUsers; }
     set
     {
         _connectedUsers = value;
         frmWebInput MyForm = new frmWebInput();
         MyForm.ConnectedUserCount.Text = String.Format("Connected Users: {0}", value);
     }
 }

public static void clientListener()
    {
        while (true)
        {
            try
            {
                HttpListenerContext request = listener.GetContext();
                ThreadPool.QueueUserWorkItem(processRequest, request);
            }
            catch (Exception e) {  }
        }
    }

public static void processRequest(object listenerContext)
{
        try
        {
           connectedUsers = connectedUsers + 1;
        }
}

Upvotes: 0

Views: 553

Answers (1)

David
David

Reputation: 218857

Is this a WinForms application running on the web server? Or is this a WebForm?

In any event, you never show the form:

frmWebInput MyForm = new frmWebInput();
MyForm.ConnectedUserCount.Text = String.Format("Connected Users: {0}", value);

Every time the value is set, you create a new instance of frmWebInput and set the text on that instance. But you never show it. If one is already shown elsewhere in the application, you never set its text.

You need a reference to the instance of the form being shown. Something like:

private static frmWebInput MyForm { get; set; }

private static int _connectedUsers = 0;
public static int connectedUsers {
    get { return _connectedUsers; }
    set
    {
        _connectedUsers = value;
        MyForm.ConnectedUserCount.Text = String.Format("Connected Users: {0}", value);
    }
}

And, of course, that reference would have to be set with the instance of the form. Since it's static it would have to be within the static initializer. Either that or instead of an auto-implemented property it can just be a get which dynamically fetches the instance of the form. It's difficult to advise on the best approach since I don't know how this code interacts with the form instance.

Upvotes: 1

Related Questions