1

我有一个名为的多行文本框txtOutput,用于接收来自串行端口的消息。每条新消息都是一个新行,代表一个从 1 到最多 4 位的数字。用于在多行文本框中添加数据的方法是追加。我对上述功能没有任何问题,它工作正常。

如果数字小于 1000,我想从最后一条消息中txtOutput显示,如果不是,则显示在中。然后两个文本框都会更新。textBox2textbox3

如果有人能举个例子,特别是如何将最后一条消息从多行文本框获取到变量以及如果有新值时如何更新文本框,我将不胜感激。

4

2 回答 2

3

You should save the last message (from the serial port) in a variable such as lastSerialMesssage. You can then convert this value to an integer and use a conditional statement to check if the value is smaller than 1000, if it is, set TextBox3 to the last serial message value, else set the value to TextBox2.

string lastSerialMessage = SerialPortMessage;

int lastMessageValue;
Int32.TryParse(lastSerialMessage, out lastMessageValue);

if (lastMessageValue < 1000)
{
   TextBox3.Text = lastSerialMessage;
} else {
   TextBox2.Text = lastSerialmessage;
}

http://msdn.microsoft.com/en-us/library/f02979c7.aspx

于 2013-04-21T14:51:42.187 回答
0

Thanks to all for the suggestions but as I mentioned in my comments, the suggested methods did not work because the content of the string was not accurate and I ended up receiving in the textBox 2 and 3 only part of the data and not always. I have solved the problem (thanks to other advices) using RegEx in this way:

 if (txtOutput.Text.Length > 0)
        {
            MatchCollection mc = Regex.Matches(txtOutput.Text, @"(\+|-)?\d+");
            if (mc.Count > 0)
            {
                long value = long.Parse(mc[mc.Count - 1].Value);
                if (value < 1000)
                {
                    textBox2.Text = value.ToString();
                }
                else
                {
                    value = value - 1000;
                    textBox3.Text = value.ToString();
                }
            }
        }

this is working fine and no piece of information are lost.Thanks again for your advices.

于 2013-04-22T04:40:38.507 回答