我試圖顯示從服務器發送到客戶端的一些數據Windows窗體應用程序。客戶端腳本是一個Windows窗體應用程序,我有一個標籤名爲LABEL1其文字我試圖顯示從服務器客戶端,但label1的文本永遠不會改變在所有接收到的數據。這是什麼原因?以下是客戶端代碼。服務器腳本是一個控制檯應用程序。與UDP
現在Program.cs是空的,Form1.cs中看起來是這樣,但我仍然獲得與label1.text同樣的錯誤:
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e)
{
GetDataFromUDP();
}
public static void SetTextForLabel(string myText)
{
label1.Text = myText;
}
private void GetDataFromUDP()
{
UdpClient subscriber = new UdpClient(8899);
IPAddress addr = IPAddress.Parse("230.0.0.1");
subscriber.JoinMulticastGroup(addr);
IPEndPoint ep = null;
for (int i = 0; i < 10; i++)
{
byte[] pdata = subscriber.Receive(ref ep);
string price = Encoding.ASCII.GetString(pdata);
//Write data to the label
SetTextForLabel(price);
}
subscriber.DropMulticastGroup(addr);
}
}
}
裏面SetTextForLabel我得到的錯誤:
An object reference is required for the non-static field, method, or property 'WindowsFormsApplication4.Form1.label1'
public static void SetTextForLabel(string myText)
{
label1.Text = myText;
}
Application.Run阻塞是不是? –
是的,你是對的。您應該在窗體的構造函數,方法或按鈕單擊處理程序中運行UDP連接的代碼。如果你不想連接阻止表單,那麼這是一個不同的故事。 –
我很快回復,卻沒有意識到他的完整代碼。 –