DataGridView 在初始化时显示数据,但随后以编程方式没有数据

DatGridView Displayes data when initialised but then has no data programatically

我有一个从 excel 数据源填充的 dataGridView。它加载良好并在初始化表单时显示数据。但是一旦加载它就没有数据。

我的表单中有绑定源 class:

BindingSource bindingSource = new BindingSource();

这是我从 excel 获取数据并填充数据网格视图的代码:

public void GetList(string fileName, string fileExt)
    {
        try
        {
            SystemData.DataTable excelDataTable = new SystemData.DataTable();

            if (fileExt == "*.xlsx")
            {
                OleDbConnection oleConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO';"); // > 2007
                OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", oleConn); // select columns
                oleAdpt.Fill(excelDataTable); // fill table
            }
            else
            {
                OleDbConnection oleConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"); // < 2007
                OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", oleConn); // select columns
                oleAdpt.Fill(excelDataTable); // fill table
            }

            bindingSource.DataSource = excelDataTable;
            dataGridView1.DataSource = bindingSource;
            dataGridView1.Visible = true;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.MultiSelect = false;
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }
    }

一旦加载并以图形方式显示数据,它会立即 returns 没有行、列、单元格和数据。它是空的。

如果我尝试获取一些数据,比如有多少行,我什么也得不到:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(dataGridView1.Rows.Count.ToString());
    }

如能帮助纠正此问题,我们将不胜感激。

使用(最终)绑定到数据 table 的 datagridview 时,如果您想了解有关数据的某些信息或对其执行某些操作,请直接对数据 table 执行操作,不是通过数据网格视图。 fill 方法完成后,唯一可以引用的是绑定源

MessageBox.Show((bindingSource.DataSource as DataTable).Rows.Count);

与其一直将 BS 的数据源转换为数据table,不如让数据table也成为 class 级变量

如果您想了解有关 DGV 中当前行的信息,请询问 BindingSource。当前表示如果用户开始输入,数据将进入的行。

bindingSource.Current 

Current 类型为 return 对象,但对您来说是一个 DataRowView,它是 bindingSource 在绑定到数据 table 时用来表示行的内容。如果你想要数据table本身中的底层行,请使用DataRowView的Row属性,否则你可以在读写数据方面将数据行视图视为数据行

(bindingSource.Current as DataRowView).Row //a datarow

(bindingSource.Current as DataRowView)["name"] 

= "约翰"; (bindingSource.Current 作为 DataRowView).Row ["name"] =“约翰”;

我建议你唯一一次向 DGV 询问任何事情是当你 select 突出显示其中的多行并使用例如它的 SelectedRows 集合时。在这些情况下,努力通过 DataBoundItem 属性 访问基础行,其中 return 是绑定源的 DataRowView,然后可用于通过其 Row 获取数据 table 的行属性

(DGV.SelectedRows[0].DataBoundItem as DataRowView).Row

这个洋葱有很多层吗?