My GUI has a datagridview in Form1 and is supposed to be populated by data from a datatable that lives in a separate class. 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. 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 not showing my columns
how to bind datatable to datagridview in c#
DataGridView does not display DataTable
Here's my code
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;
}
You need a Constructor in your LightSensor class that calls OpticalDataSetup and OpticalDataRows :
public LightSensor(){
OpticalDataSetup();
OpticalDataRows();
}
then initialize LightSensor after InitializeComponent();
LightSensor ls = new LightSensor();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.