2

我有一个可以与连接的硬件通信的应用程序。当我打开硬件时,硬件会不断地向应用程序发送一些数据。我能够从我的应用程序中的硬件读取数据。

现在我想将这些数据连续记录到网格视图中(每当应用程序接收数据时,需要将新行添加到网格视图并填充该行中的数据)。

(或者请告诉我如何每 1 秒在网格视图中添加新行并在运行时向其中添加一些数据)

请帮忙。我是 C# 的新手。

谢谢。

4

2 回答 2

1

这是给你的演示。我想您的数据类型Info如下定义,您可以Properties根据您的数据结构(从硬件接收)相应地更改:

public partial class Form1 : Form {
   public Form1(){
      InitializeComponent();
      dataGridView1.AllowUserToAddRows = false;//if you don't want this, just remove it.
      dataGridView1.DataSource = data;
      Timer t = new Timer(){Interval = 1000};
      t.Tick += UpdateGrid;
      t.Start();
   }     
   private void UpdateGrid(object sender, EventArgs e){
      char c1 = (char)rand.Next(65,97);
      char c2 = (char)rand.Next(65,97);
      data.Add(new Info() {Field1 = c1.ToString(), Field2 = c2.ToString()});
      dataGridView1.FirstDisplayedScrollingRowIndex = data.Count - 1;//This will keep the last added row visible with vertical scrollbar being at bottom.
   }
   BindingList<Info> data = new BindingList<Info>();
   Random rand = new Random();
   //the structure of your data including only 2 fields to test
   public class Info
   {
        public string Field1 { get; set; }
        public string Field2 { get; set; }
   }  
}
于 2013-07-30T07:37:11.080 回答
1

如果您在对象或变量中的某个位置获取数据,那么这对您有用。

// suppose you get the data in the object test which has two fields field1 and field2, then you can add them in the grid using below code:

grdView.Rows.Add(test.field1, test.field2);

我希望它会帮助你.. :)

于 2013-07-30T06:35:22.843 回答