简体   繁体   中英

DataGridView bound to DataTable not displaying rows

I have a DataTable that I am manually populating bound to a DataGridView for display. When I manually add a row to the DataTable, it isn't showing up in the DataGridView. The columns are there, but now rows.

Any ideas?

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

Shouldn't your code for the binding look like this?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM