从第二次或更多次调用时如何重置增量变量

时间:2018-08-23 03:16:13

标签: c# variables counter

public partial class MainForm : Form
{
    private static int lineReadCounter = 0;
    public string DataToSetandGet = String.Empty;

    private void StatusBtn_Click(object sender, EventArgs e)
    {
        string StatusInfoToshow = "?S\r";
        string commForMeter = string.Format(StatusInfoToshow);
        try
        {
            if (statusofMeter.serialPortForApp.IsOpen)
            {
                statusofMeter.serialPortForApp.Write(commForMeter);
            }
        }
        catch (Exception)
        {
            statusofMeter.ShowDataInScreenTxtb.Text = "TimeOUT Exception";
        }
    }

    public void SerialPortInApp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        DataToSetandGet = serialPortForApp.ReadExisting();
        string pattern = @"^[a-zA-Z0-9\s\-?\*?\.?\/\:\\r]{1,}$";
        Match rgxs = Regex.Match(DataToSetandGet, pattern);

        if (rgxs.Success && DataToSetandGet.Length > 50 &&
        DataToSetandGet.IndexOf("\r") == DataToSetandGet.Length - 1)
        {
            lineReadCounter++;
            this.BeginInvoke((Action)delegate ()
            {
                Textbox1.AppendText(lineReadCounter.ToString() +
                DataToSetandGet.Substring(4).Replace("\n", " ").Replace("\r", "\r\n"));
            });
        }
    }

    private void CountReadings()
    {
        //Count Readings
        string[] lines =
        Regex.Split(textbox1.Text.Trim(), "\r\n");//Trim avoid white spaces
        lineReadCounter = lines.Length;
        label1.Text = "No. Readings: " + lineReadCounter.ToString();

    }
}

如果我按下按钮StatusBtn_Click,它将发送命令并显示

lineReadCounter +阅读

lineReadCounter1开始,第一次按下该按钮。但从lineReadCounter开始2再按一次第二次和下一次。

每次按下按钮如何将lineReadCounter重置为zero1

1 个答案:

答案 0 :(得分:0)

放入

lineReadCounter = 0;

之前

statusofMeter.serialPortForApp.Write(commForMeter);

因此您的btnClick事件将如下所示:

private void StatusBtn_Click(object sender, EventArgs e)
    {
        string StatusInfoToshow = "?S\r";
        string commForMeter = string.Format(StatusInfoToshow);
        try
        {
            if (statusofMeter.serialPortForApp.IsOpen)
            {
                lineReadCounter = 0;
                statusofMeter.serialPortForApp.Write(commForMeter);
            }
        }
        catch (Exception)
        {
            statusofMeter.ShowDataInScreenTxtb.Text = "TimeOUT Exception";
        }
    }

我认为您订阅了SerialPort.DataReceived事件,因此如果您调用Write(),则会调用SerialPortInApp_DataReceived方法。我觉得对吗?