绑定到DataTable的DataGridView不显示行

时间:2012-03-31 16:47:53

标签: c# .net data-binding datagridview datatable

我有一个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;
}

1 个答案:

答案 0 :(得分:0)

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

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