111,130
社区成员
发帖
与我相关
我的任务
分享求助,为什么时间会在文本框里打印两次,怎么解决啊?
if (checkBox3.Checked) //显示时间的校验框被选中
{
textBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n"); //在接收数据的前面一行追加显示时间
}
textBox1.AppendText(serialPort1.ReadExisting());

在你的代码中,时间会在文本框里打印两次的原因是因为你在两个地方都使用了textBox1.AppendText()方法来添加文本。
首先,你在校验框被选中时,使用了textBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");来添加显示时间的文本。然后,又使用了textBox1.AppendText(serialPort1.ReadExisting());来添加接收到的数据。
要解决这个问题,你可以在添加显示时间的文本之前,先检查接收到的数据是否为空。如果为空,则不添加显示时间的文本。
以下是修改后的代码示例:
if (checkBox3.Checked) //显示时间的校验框被选中
{
string receivedData = serialPort1.ReadExisting();
if (!string.IsNullOrEmpty(receivedData))
{
textBox1.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n");
}
textBox1.AppendText(receivedData);
}
else
{
textBox1.AppendText(serialPort1.ReadExisting());
}
这样修改后,只有在接收到的数据不为空时,才会在文本框中添加显示时间的文本。