0
votes

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;
}
1
So, is AutoGenerateColumns on?TaW
@TaW I tried setting AutoGenerateColumns to both true and false. Neither had an impact on the dgv.timmebee
This should be easy to debug. Put a stop on the DataTable dataTable = LightSensor.dtOptical; line and when you reach it, step through the code line by line to see what happens.LarsTech
Please show the class header!TaW
@LarsTech Tried that...program just steps through to DGV.DataSource then to Application.Run(new Form1()) in Program.cs then goes to my GUI window.timmebee

1 Answers

3
votes

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();