簡體   English   中英

C#-如何在另一個列表框中打印字符串?

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

此代碼的一部分將打印“找到新的Ip客戶端”,我添加了一個代碼( 已注釋的部分 ),它將在其中獲取主機名。 我希望將該主機名打印在單獨的列表框中。 我該怎么辦? 我試圖附加它,但是它不會顯示在我在[設計]中提供的列表框中。

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);
        }
    }
}

謝謝。

由於您要從另一個線程引用主線程,因此不能直接這樣做。 不允許跨線程操作以防止死鎖。 請執行以下操作,從另一個線程訪問您在主線程中的列表。

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

我已經很長時間沒有使用Windows Forms了,所以請考慮一下它的價值。 將文本添加到列表框中后,嘗試執行以下操作:

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

這是您需要添加到列表框的代碼,只需將listbox1替換為列表框的名稱\\ id

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM