c# - 如何在 C# Windows 窗体中动态填充 Datagridview(运行时)

标签 c# winforms dynamic datagridview

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

现在我想连续将此数据记录到 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/

相关文章:

c# - 是否可以使此方法通用

Winforms - 如何控制复选框颜色(类似于只读文本框)

vb.net - 圆角矩形不准确

通过在 Dynamic 中使用指针将一个字符串复制到另一个字符串

c# - 如何创建具有可变参数/不同方法签名的方法接口(interface)?

c# - 为什么在 OOP(例如 Java、C#)中使用 break/continue 标签是一种不好的做法?

c# - 如何更新 ListView 选中的项目?

python - 使用 Pyparsing 根据 header 字段解析 CSV 数据

javascript - 在 JS 中创建动态变量和函数

C# 检查文件目标是否有效