我有一个可以与连接的硬件通信的应用程序。当我打开硬件时,硬件会不断地向应用程序发送一些数据。我能够从我的应用程序中的硬件读取数据。
现在我想连续将此数据记录到 GridView 中(每当应用程序接收数据时,需要将新行添加到 GridView 并填充该行中的数据)。
(或者请告诉我如何在 GridView 中每 1 秒添加新行并在运行时向其中添加一些数据)
请帮忙。我是 c# 新手。
谢谢。
最佳答案
这是为您准备的演示。我假设您的数据属于如下定义的 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; }
}
}
关于c# - 如何在 C# Windows 窗体中动态填充 Datagridview(运行时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17939619/