user3406220
user3406220

Reputation: 427

C# - How do I print a string in another listbox?

A part of this code will print the 'New Ip client found', I added a code(the commented part) where it will get the hostname. I want that hostname to be printed in a separate listbox. How should I do it? I tried to append it but it wont show in the listbox I provided in the [Design].

public void performConnect()
{
    while (true)
    {
        if (myList.Pending())
        {
            thrd = thrd + 1;
            tcpClient = myList.AcceptTcpClient();

            IPEndPoint ipEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
            string clientIP = ipEndPoint.Address.ToString();
            nStream[thrd] = tcpClient.GetStream();

            // IPHostEntry ipEntry = Dns.Resolve(clientIP);
            // string sClientHost = ipEntry.HostName;

            currentMsg = "\n New IP client found :" + clientIP;
            recieve[thrd].Start();

            //StringBuilder sb = new StringBuilder();                        
            // sb.Append(listBox1.Text);                        
            // sb.Append(sClientHost + " is online.");                       
            //listBox1.Text = sb.ToString();

            this.Invoke(new rcvData(addNotification));
            try
            {
                addToIPList(clientIP);

            }
            catch (InvalidOperationException exp)
            {
                Console.Error.WriteLine(exp.Message);
            }
            Thread.Sleep(1000);
        }
    }
}

Thank you.

Upvotes: 0

Views: 78

Answers (3)

Simon Price
Simon Price

Reputation: 3261

This is the code you need to add to the listbox, just replace the listbox1 with the name \ id of your listbox

Action action = new Action(() => { 
                listBox1.Items.Add(sClientHost); 
            });
this.Dispatcher.Invoke(action, DispatcherPriority.ApplicationIdle);

Upvotes: 0

NZeta520
NZeta520

Reputation: 114

Since you are referencing main thread from another thread, you can't just do it directly. Cross thread operation is not allowed to prevent deadlocks. Do as following to access your list which in the main thread from another thread.

lstYourListBox.BeginInvoke(new MethodInvoker(() => lstYourListView.items.Add(clientIP));

Upvotes: 1

Jeff Prince
Jeff Prince

Reputation: 678

I haven't used Windows Forms in a long time so take this for what it's worth. Try doing the following after you add the text to the listbox:

listBox1.Invalidate();
listBox1.Update();

Upvotes: 0

Related Questions