我的GUI在Form1中具有datagridview,应该由位于单独类中的数据表中的数据填充。我已经设置了绑定源和数据源,但是当我运行GUI时,datagridview为空白,并且不显示数据表中的列。此时,我不存储行的任何数据,我只想确保显示我的列标题。
我查看了以下所有链接,但到目前为止没有任何帮助:
DataGridView not showing Columns/Data
DataGridView not showing my columns
how to bind datatable to datagridview in c#
DataGridView does not display DataTable
这是我的代码
Form1.cs:
using System;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
public Form1()
{
InitializeComponent();
DataTable dataTable = LightSensor.dtOptical;
DGV.DataSource = dataTable;
}
LightSensor.cs:
using System;
using System.Data;
using System.IO.Ports;
using System.Threading.Tasks;
using System.Windows.Forms;
public static DataTable dtOptical = new DataTable();
BindingSource bindingSource = new BindingSource();
private void OpticalDataSetup()
{
dtOptical.Columns.Add("Sequence");
dtOptical.Columns.Add("Date");
dtOptical.Columns.Add("Time");
}
private void OpticalDataRows()
{
DataRow row = dtOptical.NewRow();
row = dtOptical.NewRow();
row["Sequence"] = MeasSeq;
row["Date"] = DateTime.Today.ToString("MM-dd-yyyy");
row["Time"] = DateTime.Now.ToString("HH:mm:ss");
dtOptical.Rows.Add(row);
bindingSource.DataSource = dtOptical;
}
答案 0 :(得分:3)
您需要在LightSensor类中构造一个构造函数,该构造函数调用 OpticalDataSetup 和 OpticalDataRows :
public LightSensor(){
OpticalDataSetup();
OpticalDataRows();
}
然后在InitializeComponent()之后初始化LightSensor;
LightSensor ls = new LightSensor();