Datagridview会添加不需要的行

时间:2013-06-22 06:32:46

标签: c# datagridview

每次变量“temperature”和“umidita”显示在相关文本框中时,此代码的最后一行应该在datagridview中填入一行3列。

这些数据来自串口,每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 });
        }
    }

代码正在运行,但我在使用相同的数据填充了3行。

enter image description here

我不熟悉datagridview,我不明白为什么我会遇到这样的行为。我需要改变什么才能及时填充一行,“Temperatura”和“umidita”?

1 个答案:

答案 0 :(得分:0)

////您可以检查此时是否已插入行

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 });
        }
相关问题