【问题标题】:Column count does not match in DataTable and (databound) DataGridviewDataTable 和(数据绑定)DataGridview 中的列数不匹配
【发布时间】:2013-03-10 16:31:42
【问题描述】:

我与DataGridViewDataTable 合作已久。但我一直无法确定为什么/如何有时(不是到处)DataGridvVewDataTable 中的列数不匹配,即使我将我的 Datatable 设置为 DataSource 为我的 DataGridView

myGrid.DataSource = myTable;
myGrid.Refresh();
MessageBox.Show(myTable.Columns.Count+"--"+myGrid.Columns.Count);// shows 5--0

编辑:(对第一条评论的回答)这里我的 DataTable 被创建为

DataTable myTable = new DataTable();
myTable.Columns.Add("Col1", typeof(int));
myTable.Columns.Add("Col2", typeof(string));
myTable.Columns.Add("Col3", typeof(string));

【问题讨论】:

  • 我们能否看看 myTable 在其中一种糟糕的情况下是如何创建的。
  • 是的。为什么不。 @Mike C。我已经展示过了。
  • 你的 DataGridView.AutoGenerateColumns 属性是否有真值?
  • 我测试了你的代码,但它似乎是正确的。 DataTable 有 3 列,DataGridView 也有 3 列。
  • 在刷新前尝试 myGrid.DataBind()

标签: c# .net winforms datagridview


【解决方案1】:

当我将 DataGridView 控件放入 TabControl 时,我遇到了同样的问题。

DataGridView 控件位于 TabControl 的第二个选项卡上,默认情况下它在启动时不显示,当我切换到第二个选项卡时,我在实现的 DataGridView_CellFormatting 事件中遇到了问题。

我从微软找到this

“在标签页显示之前不会创建 TabPage 中包含的控件,并且在显示标签页之前不会激活这些控件中的任何数据绑定。”

我通过将以下代码行添加到我的 Form_Load 事件来解决我的问题:

tabControl1.SelectTab(1); //Selects the second tab

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多