如何在C#Win表单中动态填充数据网格视图(运行时)

如何在C#Win表单中动态填充数据网格视图(运行时),c#,winforms,dynamic,datagridview,C#,Winforms,Dynamic,Datagridview,我有一个应用程序可以与连接的硬件通信。当我打开硬件时,硬件会不断地向应用程序发送一些数据。我能够从应用程序中的硬件读取数据 现在我想连续地将这些数据记录到网格视图中(每当应用程序接收到数据时,都需要向网格视图中添加一个新行,并填充该行中的数据) (或者,请演示如何在网格视图中每隔1秒添加新行,并在运行时向其中添加一些数据) 请帮忙。我是c#的新手 谢谢。如果您在对象或变量中的某个位置获得数据,那么这将适用于您 // suppose you get the data in the object t

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

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

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

请帮忙。我是c#的新手


谢谢。

如果您在对象或变量中的某个位置获得数据,那么这将适用于您

// 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);

我希望它能帮助你……)

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

公共部分类表单1:表单{
公共表格1(){
初始化组件();
dataGridView1.AllowUserToAddress=false;//如果您不想要它,只需删除它即可。
dataGridView1.DataSource=数据;
定时器t=新定时器(){Interval=1000};
t、 Tick+=UpdateGrid;
t、 Start();
}     
私有void UpdateGrid(对象发送方,事件参数){
char c1=(char)rand.Next(65,97);
char c2=(char)rand.Next(65,97);
Add(新信息(){Field1=c1.ToString(),Field2=c2.ToString()});
dataGridView1.FirstDisplayedScrollingRowIndex=data.Count-1;//这将保持最后添加的行可见,垂直滚动条位于底部。
}
BindingList数据=新建BindingList();
Random rand=新的Random();
//数据的结构只包括两个要测试的字段
公共类信息
{
公共字符串字段1{get;set;}
公共字符串字段2{get;set;}
}  
}
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; }
   }  
}