C# 我得到一个错误,我在表单头而不是文本框中获取数据
这是我通过套接字连接的客户机获取数据的代码,但我获取的数据是表单标题,而不是文本框C# 我得到一个错误,我在表单头而不是文本框中获取数据,c#,C#,这是我通过套接字连接的客户机获取数据的代码,但我获取的数据是表单标题,而不是文本框 // Buffer for reading data Byte[] bytes = new Byte[4096]; String data = null; //Enter the listening loop while (true) { txtOutput.Text = "Waiting For Connec
// Buffer for reading data
Byte[] bytes = new Byte[4096];
String data = null;
//Enter the listening loop
while (true)
{
txtOutput.Text = "Waiting For Connection... to get started";
//blocks until a client is connected to server
TcpClient tcpClient = server.AcceptTcpClient();
txtOutput.Text = "Connected!..";
data = null;
// Get a stream object for reading and writing
NetworkStream netStream = tcpClient.GetStream();
int i;
//loop to receive all data sent by the client
while ((i = netStream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
//data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//txtOutput.Text = data;
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(bytes, 0, 4096));
Text += "\n" + Encoding.Default.GetString(bytes,0,i);
txtOutput.Invoke(new Action(() => txtOutput.Text += text));
}
// Shutdown and end connection
tcpClient.Close();
}
更新 请注意,在调用之前,您正在将数据分配给
Text
。在调用内部,您试图将text
的内容分配给文本框。这不是一回事。按如下所示更改针对表单文本属性的以下行:
// Text += "\n" + Encoding.Default.GetString(bytes,0,i);
text += "\n" + Encoding.Default.GetString(bytes,0,i);
指定给此行中的文本框时
txtOutput.Invoke(new Action(() => txtOutput.Text += text));
您是从一个
text
变量(小T)赋值,而不是将值放入其中的text
(大T)。大T文本是表单的文本属性,它将更改表单标题,正如您在此处所说。现在查看我的答案。我已经根据您的评论和我在查看代码后在代码中看到的其他内容对其进行了更改。请注意,在代码中,您使用大写字母T来指定文本,如text+=…
中所示,而您则从txtOutput.text+=text
中指定给文本框。区分大小写使这些对象不同。大写的T one是表单的文本属性,小的T是一个变量,我假设您在共享的代码之外定义了它。我已经纠正了这个问题,但问题仍然是一样的