【问题标题】:DataGridView not showing columns from DataTable C#DataGridView 不显示来自 DataTable C# 的列
【发布时间】:2019-12-16 15:04:27
【问题描述】:

我的 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;
}

【问题讨论】:

  • 那么,AutoGenerateColumns 开启了吗?
  • @TaW 我尝试将 AutoGenerateColumns 设置为 true 和 false。两者都对 dgv 没有影响。
  • 这应该很容易调试。在DataTable dataTable = LightSensor.dtOptical; 行停下来,当你到达它时,逐行浏览代码,看看会发生什么。
  • 请出示班级标题!
  • @LarsTech 试过了...程序只是进入 DGV.DataSource 然后进入 Program.cs 中的 Application.Run(new Form1()) 然后进入我的 GUI 窗口。

标签: c# .net user-interface datagridview datatable


【解决方案1】:

您需要在 LightSensor 类中调用 OpticalDataSetupOpticalDataRows

public LightSensor(){
 OpticalDataSetup();
 OpticalDataRows();
}

然后在 InitializeComponent() 之后初始化 LightSensor;

LightSensor ls = new LightSensor();

【讨论】:

  • 要么使所有部分静态;要么那么就不需要实例了。如果类是statis,它应该是static LightSensor() {..但是无论如何都需要构造函数。
  • 解决了!我只是错过了对 OpticalDataSetup() 的调用。我没有使用您的方法,而是添加了 LightSensor.OpticalDataSetup();在我的 Form1 之后 InitializeComponent();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多