简体   繁体   English

Datagridview加起来不需要的行

[英]Datagridview adds up unwanted rows

The last line of this code is supposed to fill in a row with 3 columns in a datagridview every time the variable "temperature" and "umidita" are shown in the relevant text boxes. 每次在相关文本框中显示变量“ temperature”和“ umidita”时,该代码的最后一行应在datagridview中用3列填充一行。

These data comes from the serial port and get updated every x seconds. 这些数据来自串行端口,每x秒更新一次。

private void SetText(string text)
    {
        string temperatura;
        string umidita;

        if (this.txtOutput.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.BeginInvoke(d, new object[] { text });
        }

        else
        {

            string f = text;
            char firstChar = f[0];

            if (firstChar == 'T')
            {
                temperatura = f;
                temperatura = f.Replace("T", "");
                textBox1.Text = temperatura;
            }

            else if (firstChar == 'U')
            {
                umidita = f;
                umidita = f.Replace("U", "");
                textBox2.Text = umidita;
            }
            dataGridView1.Rows.Add(new string[] { DateTime.Now.ToString("HH:mm:ss"), textBox1.Text, textBox2.Text });
        }
    }

The code is working but I get 3 rows at time filled in with the same data. 该代码正在运行,但是我一次获得了3行,并填充了相同的数据。

在此处输入图片说明

I am not familiar with datagridview and I do not understand why I am getting such behavior. 我不熟悉datagridview,也不清楚为什么会出现这种行为。 What do I need to change to get one row at time filled in with time, "temperatura" and "umidita"? 我需要更改什么才能在时间上填充“ temperatura”和“ umidita”一行?

////you can check if you already inserted a row in this time ////您可以检查这一次是否已插入行

int rowsCount = dataGridView1.Rows.Count;
        string cuurentTime = DateTime.Now.ToString("HH:mm:ss");
        if (cuurentTime != dataGridView1.Rows[rowsCount - 1].Cells[0].Value.ToString())
        {
            dataGridView1.Rows.Add(new string[] { cuurentTime, textBox1.Text, textBox2.Text });
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM