[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 735
  • Last Modified:

c# listbox not working

I am attempting to add a username to a listbox at runtime as they connect to my server app.  The listbox is updated when i check it in the code, i.e. when i debug the code, all the entrys are displayed, however, the actual listbox on the display is never updated, if i put the command in the form load the item is added.

I have tryed a this.refresh, lstItems.Update(), lstItems.Refresh() all dont work

Thanks
Tom
lstItems.Item.Add(Username);

Open in new window

0
delta_v
Asked:
delta_v
1 Solution
 
SaedSalmanCommented:
lstItems.Items.Add(Username); \\Itemes (not item)

> I have tryed a this.refresh, lstItems.Update(), lstItems.Refresh() all dont work
Where you did this.refresh, lstItems.Update(), lstItems.Refresh()

> I have tryed a this.refresh, lstItems.Update(), lstItems.Refresh() all dont work
you meant lstItems.Refresh not this.refresh right ?
0
 
delta_vAuthor Commented:
I tried all 3 after the update of the list box and yes, i was typing the code, the actual code is below.
public void AddUser(string Name)
        {
            //Add the user onto the 
             lstUsers.Items.Add(Name);
             lstUsers.Refresh();
        }

Open in new window

0
 
cmrobertsonCommented:
have you tried refreshing the form itself?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
delta_vAuthor Commented:
yes, i have used this.refresh();
0
 
CebikCommented:
are you shure that you are filling correct listbox?
look on items list in debug mode (breakepoint)
check name of the control
make sample test application
0
 
CebikCommented:
put your code
for example here: http://www.sendspace.com/
we will check code
0
 
delta_vAuthor Commented:
I am filling the correct list box, i only have one list box on my form at the moment.

the code is above

when i debug the code the count has gone up and if show the last entry in the list box in a message box, i.e. MessageBox.Show (lstUser.Items[lstUsers.Items.Count - 1]), the entry is shown correctly.
0
 
CebikCommented:
put whole your application..

i made simple application and i haven't any problem..
everythinks works good even without refresh

private void button1_Click(object sender, EventArgs e)
{
    listBox1.Items.Add("xxxx");
}

Open in new window

0
 
delta_vAuthor Commented:
This is the main form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
 
 
namespace STD_Server
{
    public partial class frmMain : Form
    {
        #region//Varaibles\\
        public bool bolOnline       = false,
                    bolRaw          = true; 
 
 
 
 
        #endregion
 
        #region//Constants\\
        public const string _strOfflineLabel        = "The server is offline",
                            _strOnlineLabel         = "The server is online and accepting connections to ",
                            _strOfflineButton       = "Put Server Online",
                            _strProgramName         = "Server Transmitted Data",
                            _strProgramAbbrivation  = "STD";
 
        public const int    _intMaxUsers            = 30;
 
        #endregion
 
        private delegate void UpdateStatusCallback(string strMessage);
 
        public frmMain()
        {
            InitializeComponent();
        }
 
        /// <summary>
        /// Sets up the initial variables for the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <AuthorName>TT</AuthorName>
        /// <DateWritten>08/04/2009</DateWritten>
        private void frmMain_Load(object sender, EventArgs e)
        {
            //Stats Variables TT\\
            bolOnline = false;
            chkRaw.Checked = true;
            bolRaw = true;
            
        }
 
        #region//Server Status\\
        /// <summary>
        /// Switch the server state
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdStatus_Click(object sender, EventArgs e)
        {
            //Check which state the server is in TT\\
            if (!bolOnline)
            {
                //The server is offline, run the put online script TT\\
                PutServerOnline();
            }
        }
 
        /// <summary>
        /// Puts the server into the online state
        /// </summary>
        /// <returns  name="Success"></returns>
        /// <AuthorName>TT</AuthorName>
        /// <DateWritten>08/04/2009</DateWritten>
        private bool PutServerOnline()
        {
            #region//Set up local variables TT\\
            bool bolSuccess = false;
            #endregion
 
            #region//Try and start the server TT\\
            try
            {
                //Set IP Address TT\\
                IPAddress ipAddr = IPAddress.Parse(Functions.GetIPAddress());
 
                //Start the Server TT\\
                _Server Server = new _Server(ipAddr);
                _Server.StatusChanged += new StatusChangedEventHandler(Server_StatusChanged);
                Server.StartListening();
 
                //Inform the program and the user that the server is online TT\\
                txtRaw.AppendText("The server is now online and accepting messages on " + ipAddr + " \r\n");
                bolSuccess = true;
            }
            #endregion
 
            #region//If the server didn't start TT\\
            catch
            {
                //The server did not succesfully start TT\\
                bolSuccess = false;
            }
            #endregion
 
            #region//Check if the server has successfuly been put online TT\\
            if (bolSuccess)
            {
                //Add a test message\\
 
                //Set the display to show the server is online TT\\
                this.Text = _strProgramName + " - Online";
                cmdStatus.Visible = false;
                lblStatus.Left = cmdStatus.Left;
                lblStatus.Text = _strOnlineLabel + Functions.GetIPAddress();
 
                //Set the Online variable to false TT\\
                bolOnline = true;
            }
            #endregion
 
            #region//Return the outcome TT\\
            return bolSuccess;
            #endregion
        }
 
        public void Server_StatusChanged(object sender, StatusChangedEventArgs e)
        {
            // Call the method that updates the form
            try
            {
                this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
            }
            catch
            {
 
            }
        }
 
        /// <summary>
        /// Adds the message to the raw if required
        /// </summary>
        /// <param name="strMessage"></param>
        /// <AuthorName>TT</AuthorName>
        /// <DateWritten>09/04/2009</DateWritten>
        private void UpdateStatus(string strMessage)
        {
            //Check if raw data is requested TT\\
            if (chkRaw.Checked == true)
            {
                //Add the raw message to the raw data box TT\\
                txtRaw.AppendText(strMessage + "\r\n");
                strMessage = null;
            }
        }
 
        #endregion
 
        public void AddUser(string Name)
        {
            //Add the user onto the 
             lstUsers.Items.Add(Name);
             lstUsers.Refresh();
        }
        public void RemoveUser(string Name)
        {
            try
            {
                lstUsers.Items.Remove(Name);
            }
            catch
            {
                MessageBox.Show("ERRROR");
            }
        }
        public void AppendRaw(string Message)
        {
            if (bolRaw)
            {
                txtRaw.AppendText(Message);
            }
        }
        private void chkRaw_CheckedChanged(object sender, EventArgs e)
        {
            bolRaw = chkRaw.Checked;
        }
 
        private void cmdSend_Click(object sender, EventArgs e)
        {
            _Server.SendMessage("This is a single user test", "Tom Turner");
        }
 
    }
}

Open in new window

0
 
delta_vAuthor Commented:
The server.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Collections;
 
namespace STD_Server
{
    #region// Holds the arguments for the StatusChanged event - Needs to be commented
    public class StatusChangedEventArgs : EventArgs
    {
        // The argument we're interested in is a message describing the event
        private string EventMsg;
 
        // Property for retrieving and setting the event message
        public string EventMessage
        {
            get
            {
                return EventMsg;
            }
            set
            {
                EventMsg = value;
            }
        }
 
        // Constructor for setting the event message
        public StatusChangedEventArgs(string strEventMsg)
        {
            frmMain Main = new frmMain();
            if (Main.bolRaw)
            {
                Main.AppendRaw(strEventMsg);
            }
            EventMsg = strEventMsg;
        }
    }
    #endregion
 
    // This delegate is needed to specify the parameters we're passing with our event
    public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);
 
    class _Server
    {
        #region//Variables and arrays\\
        //Set the Hash tables to store users and connections TT\\
        public static Hashtable htUsers         = new Hashtable(frmMain._intMaxUsers);
        public static Hashtable htConnections   = new Hashtable(frmMain._intMaxUsers);
 
        // Will store the IP address passed to it
        private IPAddress ipAddress;
        private TcpClient tcpClient;
 
        // The event and its argument will notify the form when a user has connected, disconnected, send message, etc.
        public static event StatusChangedEventHandler StatusChanged;
        private static StatusChangedEventArgs e;
 
        // The thread that will hold the connection listener
        private Thread thrListener;
 
        // The TCP object that listens for connections
        private TcpListener tlsClient;
 
        // Will tell the while loop to keep monitoring for connections
        bool ServRunning = false;
        #endregion
 
        /// <summary>
        /// This sets the IP Address
        /// </summary>
        /// <param name="address"></param>
        public _Server(IPAddress address)
        {
            ipAddress = address;
        }
 
        /// <summary>
        /// Add the user to the hash tables
        /// </summary>
        /// <param name="tcpUser"></param>
        /// <param name="strUsername"></param>
        public static void AddUser(TcpClient tcpUser, string strUsername)
        {
            //Allow a connection to the add user function on the main form\\
            frmMain MainForm = new frmMain();
 
            // First add the username and associated connection to both hash tables
            _Server.htUsers.Add(strUsername, tcpUser);
            _Server.htConnections.Add(tcpUser, strUsername);
 
            MainForm.AddUser(htConnections[tcpUser].ToString());
 
 
            // Tell of the new connection to all other users and to the server form
            SendMessage(htConnections[tcpUser] + " has joined us", null);
        }
 
        /// <summary>
        /// Remove the user from the hash tables
        /// </summary>
        /// <param name="tcpUser"></param>
        public static void RemoveUser(TcpClient tcpUser)
        {
            // If the user is there
            if (htConnections[tcpUser] != null)
            {
                string name = htConnections[tcpUser].ToString();
                // Remove the user from the hash table
                _Server.htUsers.Remove(_Server.htConnections[tcpUser]);
                _Server.htConnections.Remove(tcpUser);
                // First show the information and tell the other users about the disconnection
                SendMessage("Admin", name + " has left us");
 
                
            }
        }
 
        /// <summary>
        /// This is called when we want to raise the StatusChanged event
        /// </summary>
        /// <param name="e"></param>
        public static void OnStatusChanged(StatusChangedEventArgs e)
        {
            StatusChangedEventHandler statusHandler = StatusChanged;
            if (statusHandler != null)
            {
                // Invoke the delegate
                statusHandler(null, e);
            }
        }
            
        /// <summary>
        /// Send a message to all users
        /// </summary>
        /// <param name="From"></param>
        /// <param name="Message"></param>
        public static void SendMessage(string Message, string To)
        {
            //Set up the stream writter TT\\
            StreamWriter swSender;
 
            //Update the Raw log TT\\
            e = new StatusChangedEventArgs(Message);
            OnStatusChanged(e);
            
 
            //Create an array of users as this can be accessed more easily TT\\
            TcpClient[] tcpClients = new TcpClient[_Server.htUsers.Count];
            //Copy the user list into the new array TT\\
            _Server.htUsers.Values.CopyTo(tcpClients, 0);
 
            //Loop through the list of users TT\\
            for (int i = 0; i < tcpClients.Length; i++)
            {
                //Try to send a message to the user TT\\
                try
                {
                    //Check the is not null and the client exists TT\\
                    if (Message.Trim() == "" || 
                        tcpClients[i] == null)
                    {
                        continue;
                    }
                    //If no specific user has been selected or the to is selected TT\\
                    if (To == null || 
                        To == tcpClients[i].ToString())
                    {
                        //Send the message to the current user TT\\
                        swSender = new StreamWriter(tcpClients[i].GetStream());
                        swSender.WriteLine(Message);
                        swSender.Flush();
                    }
                }
                //If there has been an error remove the user TT\\
                catch
                {
                    RemoveUser(tcpClients[i]);
                }
            }
        }
 
        public void StartListening()
        {
 
            // Get the IP of the first network device, however this can prove unreliable on certain configurations
            IPAddress ipaLocal = ipAddress;
 
            // Create the TCP listener object using the IP of the server and the specified port
            tlsClient = new TcpListener(ipAddress, 1986);
 
            // Start the TCP listener and listen for connections
            tlsClient.Start();
 
            // The while loop will check for true in this before checking for connections
            ServRunning = true;
 
            // Start the new tread that hosts the listener
            thrListener = new Thread(KeepListening);
            thrListener.Start();
        }
        
        private void KeepListening()
        {
            // While the server is running
            while (ServRunning == true)
            {
                // Accept a pending connection
                tcpClient = tlsClient.AcceptTcpClient();
                // Create a new instance of Connection
                Connection newConnection = new Connection(tcpClient);
            }
        }
 
    }
    #region//Connection\\
    /// <summary>
    /// Handels connections,
    /// Each user will have a connection of there own
    /// </summary>
    class Connection
    {
        TcpClient tcpClient;
        // The thread that will send information to the client
        private Thread thrSender;
        private StreamReader srReceiver;
        private StreamWriter swSender;
        private string currUser;
        private string strResponse;
 
        // The constructor of the class takes in a TCP connection
        public Connection(TcpClient tcpCon)
        {
            tcpClient = tcpCon;
            // The thread that accepts the client and awaits messages
            thrSender = new Thread(AcceptClient);
            // The thread calls the AcceptClient() method
            thrSender.Start();
        }
 
        private void CloseConnection()
        {
            // Close the currently open objects
            tcpClient.Close();
            srReceiver.Close();
            swSender.Close();
        }
 
        // Occures when a new client is accepted
        private void AcceptClient()
        {
            srReceiver = new System.IO.StreamReader(tcpClient.GetStream());
            swSender = new System.IO.StreamWriter(tcpClient.GetStream());
 
            // Read the account information from the client
            currUser = srReceiver.ReadLine();
 
            // We got a response from the client
            if (currUser != "")
            {
                // Store the user name in the hash table
                if (_Server.htUsers.Contains(currUser) == true)
                {
                    // 0 means not connected
                    swSender.WriteLine("0|This username already exists.");
                    swSender.Flush();
                    CloseConnection();
                    return;
                }
                else if (currUser == "Administrator")
                {
                    // 0 means not connected
                    swSender.WriteLine("0|This username is reserved.");
                    swSender.Flush();
                    CloseConnection();
                    return;
                }
                else
                {
                    // 1 means connected successfully
                    swSender.WriteLine("1");
                    swSender.Flush();
 
                    // Add the user to the hash tables and start listening for messages from him
                    _Server.AddUser(tcpClient, currUser);
                }
            }
            else
            {
                CloseConnection();
                return;
            }
 
            try
            {
                // Keep waiting for a message from the user
                while ((strResponse = srReceiver.ReadLine()) != "")
                {
                    // If it's invalid, remove the user
                    if (strResponse == null)
                    {
                        _Server.RemoveUser(tcpClient);
                    }
                    else
                    {
                        // Otherwise send the message to all the other users
                        _Server.SendMessage(strResponse, null);
                    }
                }
            }
            catch
            {
                // If anything went wrong with this user, disconnect him
                _Server.RemoveUser(tcpClient);
            }
        }
    }
    #endregion
 
 
}

Open in new window

0
 
delta_vAuthor Commented:
The functions class
0
 
delta_vAuthor Commented:
woops forgot to add the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace STD_Server
{
    class Functions
    {
        /// <summary>
        /// Converts a string to MD5
        /// </summary>
        /// <param name="input"></param>
        /// <returns>MD5 String</returns>
        /// http://blog.brezovsky.net/en-text-2.html
        public static string MD5(string input)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider MD5Convert = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = MD5Convert.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string output = s.ToString();
            return output;
        }
 
        /// <summary>
        /// Get the Computers IP Address
        /// </summary>
        /// <returns>IP Address</returns>
        public static string GetIPAddress()
        {
            //Loop Back\\
            return "127.0.0.1";
            //return "169.254.154.235";
 
        }
 
    }
}

Open in new window

0
 
delta_vAuthor Commented:
and if you need it, the form design
namespace STD_Server
{
    partial class frmMain
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;
 
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }
 
        #region Windows Form Designer generated code
 
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.cmdStatus = new System.Windows.Forms.Button();
            this.lblStatus = new System.Windows.Forms.Label();
            this.txtRaw = new System.Windows.Forms.TextBox();
            this.chkRaw = new System.Windows.Forms.CheckBox();
            this.lstUsers = new System.Windows.Forms.ListBox();
            this.cmdKick = new System.Windows.Forms.Button();
            this.cmdSend = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // cmdStatus
            // 
            this.cmdStatus.Location = new System.Drawing.Point(11, 8);
            this.cmdStatus.Name = "cmdStatus";
            this.cmdStatus.Size = new System.Drawing.Size(104, 22);
            this.cmdStatus.TabIndex = 0;
            this.cmdStatus.Text = "Put Server Online";
            this.cmdStatus.UseVisualStyleBackColor = true;
            this.cmdStatus.Click += new System.EventHandler(this.cmdStatus_Click);
            // 
            // lblStatus
            // 
            this.lblStatus.AutoSize = true;
            this.lblStatus.Location = new System.Drawing.Point(121, 17);
            this.lblStatus.Name = "lblStatus";
            this.lblStatus.Size = new System.Drawing.Size(103, 13);
            this.lblStatus.TabIndex = 1;
            this.lblStatus.Text = "The Server is Offline";
            // 
            // txtRaw
            // 
            this.txtRaw.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtRaw.Location = new System.Drawing.Point(11, 409);
            this.txtRaw.Multiline = true;
            this.txtRaw.Name = "txtRaw";
            this.txtRaw.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtRaw.Size = new System.Drawing.Size(494, 114);
            this.txtRaw.TabIndex = 2;
            // 
            // chkRaw
            // 
            this.chkRaw.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.chkRaw.AutoSize = true;
            this.chkRaw.Location = new System.Drawing.Point(11, 386);
            this.chkRaw.Name = "chkRaw";
            this.chkRaw.Size = new System.Drawing.Size(104, 17);
            this.chkRaw.TabIndex = 3;
            this.chkRaw.Text = "Show Raw Data";
            this.chkRaw.UseVisualStyleBackColor = true;
            this.chkRaw.CheckedChanged += new System.EventHandler(this.chkRaw_CheckedChanged);
            // 
            // lstUsers
            // 
            this.lstUsers.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)));
            this.lstUsers.FormattingEnabled = true;
            this.lstUsers.Location = new System.Drawing.Point(11, 40);
            this.lstUsers.Name = "lstUsers";
            this.lstUsers.Size = new System.Drawing.Size(161, 342);
            this.lstUsers.TabIndex = 4;
            // 
            // cmdKick
            // 
            this.cmdKick.Location = new System.Drawing.Point(178, 72);
            this.cmdKick.Name = "cmdKick";
            this.cmdKick.Size = new System.Drawing.Size(93, 26);
            this.cmdKick.TabIndex = 5;
            this.cmdKick.Text = "Kick User";
            this.cmdKick.UseVisualStyleBackColor = true;
            // 
            // cmdSend
            // 
            this.cmdSend.Location = new System.Drawing.Point(178, 40);
            this.cmdSend.Name = "cmdSend";
            this.cmdSend.Size = new System.Drawing.Size(93, 26);
            this.cmdSend.TabIndex = 6;
            this.cmdSend.Text = "Send Message";
            this.cmdSend.UseVisualStyleBackColor = true;
            this.cmdSend.Click += new System.EventHandler(this.cmdSend_Click);
            // 
            // frmMain
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(517, 535);
            this.Controls.Add(this.cmdSend);
            this.Controls.Add(this.cmdKick);
            this.Controls.Add(this.lstUsers);
            this.Controls.Add(this.chkRaw);
            this.Controls.Add(this.txtRaw);
            this.Controls.Add(this.lblStatus);
            this.Controls.Add(this.cmdStatus);
            this.Name = "frmMain";
            this.Text = "ServerTransmitted Data - Offline";
            this.Load += new System.EventHandler(this.frmMain_Load);
            this.ResumeLayout(false);
            this.PerformLayout();
 
        }
 
        #endregion
 
        private System.Windows.Forms.Button cmdStatus;
        private System.Windows.Forms.Label lblStatus;
        private System.Windows.Forms.TextBox txtRaw;
        private System.Windows.Forms.CheckBox chkRaw;
        private System.Windows.Forms.ListBox lstUsers;
        private System.Windows.Forms.Button cmdKick;
        private System.Windows.Forms.Button cmdSend;
    }
}

Open in new window

0
 
CebikCommented:
You are making here new Form!
On this form you will get new item in listbox..
are you showing this form later ???
MainForm.Show() ??

  public static void AddUser(TcpClient tcpUser, string strUsername)
        {
            //Allow a connection to the add user function on the main form\\
            frmMain MainForm = new frmMain();
 
            // First add the username and associated connection to both hash tables
            _Server.htUsers.Add(strUsername, tcpUser);
            _Server.htConnections.Add(tcpUser, strUsername);
 
            MainForm.AddUser(htConnections[tcpUser].ToString());
 

Open in new window

0
 
CebikCommented:
btw nice code... and a lot of comments :)
0
 
CebikCommented:
i'm a little bit lazy
can you put your app.. or example app with this on upload site..
0
 
delta_vAuthor Commented:
0
 
CebikCommented:
The requested URL /STD-Server.zip was not found on this server.
0
 
delta_vAuthor Commented:
Woops, it was the making a new form i had run the code on the new unshown form, once i showed it, it worked
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now