绑定到DataTable的DataGridView未显示行

本文关键字:显示 DataGridView DataTable 绑定 | 更新日期: 2023-09-27 18:29:47

我有一个手动填充的DataTable绑定到DataGridView以供显示。当我手动将一行添加到DataTable时,它不会显示在DataGridView中。列在那里,但现在是行。

有什么想法吗?

((DataTable)((BindingSource)_dgv.DataSource)).Rows.Count // 2
_dgv.Rows.Count // 0
_dgv.Columns[0].IsDataBound // true, for all columns
//code that adds rows
DataRow productRow = dataTable.NewRow();
SetRowValues(productRow);
dataTable.Rows.Add(productRow);
//code to bind DataTable to DGV
BindingSource bindingSrc = new BindingSource();
bindingSrc.DataSource = dataTable;
DataGridView dgv = CreateDataGridView();
dgv.DataSource = bindingSrc;
private DataGridView CreateDataGridView()
{
    DataGridView dgv = new DataGridView();
    dgv.Anchor = (AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top);
    dgv.ShowEditingIcon = false;
    dgv.RowHeadersVisible = false;
    dgv.ReadOnly = true;
    dgv.AllowUserToAddRows = false;
    dgv.ColumnHeadersVisible = true;
    dgv.CellDoubleClick += new DataGridViewCellEventHandler(OnDGVCellDoubleClick);
    dgv.SelectionChanged += new EventHandler(OnDGVSelectionChanged);
    dgv.AutoGenerateColumns = false;
    List<OpportunityProductField> configFields = GetConfigFields();
    List<DataGridViewColumn> columns = CreateDGVColumns(configFields);
    columns.Sort(delegate(DataGridViewColumn c1, DataGridViewColumn c2) { return c1.DisplayIndex.CompareTo(c2.DisplayIndex); });
    columns.ForEach(delegate(DataGridViewColumn c) { dgv.Columns.Add(c); });
    return dgv;
}

绑定到DataTable的DataGridView未显示行

绑定的代码不应该是这样的吗?

BindingSource bindingSrc = new BindingSource();
bindingSrc.DataSource = dataTable
DataGridView dgv = CreateDataGridView();
dgv.DataSource = bindingSrc;