[英]DataGridView not showing columns from DataTable C#
My GUI has a datagridview in Form1 and is supposed to be populated by data from a datatable that lives in a separate class. 我的GUI在Form1中具有datagridview,应该由位于单独类中的数据表中的数据填充。 I have set up the binding source and data source, but when I run my GUI, the datagridview is blank and does not show the columns from my datatable. 我已经设置了绑定源和数据源,但是当我运行GUI时,datagridview为空白,并且不显示数据表中的列。 At this point I'm not storing any data for the rows, I just want to make sure my column headers get displayed. 此时,我不会为行存储任何数据,我只想确保显示我的列标题。
I have looked at all the following links and nothing has helped so far: 我查看了以下所有链接,但到目前为止没有任何帮助:
DataGridView not showing Columns/Data DataGridView不显示列/数据
DataGridView not showing my columns DataGridView不显示我的列
how to bind datatable to datagridview in c# 如何在C#中将数据表绑定到datagridview
DataGridView does not display DataTable DataGridView不显示DataTable
Here's my code 这是我的代码
Form1.cs: 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: 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;
}
You need a Constructor in your LightSensor class that calls OpticalDataSetup and OpticalDataRows : 您在LightSensor类中需要一个构造函数,该构造函数调用OpticalDataSetup和OpticalDataRows :
public LightSensor(){
OpticalDataSetup();
OpticalDataRows();
}
then initialize LightSensor after InitializeComponent(); 然后在InitializeComponent()之后初始化LightSensor;
LightSensor ls = new LightSensor();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.