DataTable 和(数据绑定)DataGridview 中的列数不匹配 [英] Column count does not match in DataTable and (databound) DataGridview

查看:24
本文介绍了DataTable 和(数据绑定)DataGridview 中的列数不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我长期使用 DataGridViewDataTable.但是我一直无法确定为什么/如何有时(不是所有地方)列数在 DataGridvVewDataTable 中不匹配,即使我已经放置了 Datatablecode> 作为 DataSource 用于我的 DataGridView.

I am working with DataGridView and DataTable for long. But I have been unable to identify why/how sometimes(not everywhere) Column count does not match in DataGridvVew and DataTable even when I have put my Datatable as DataSource for my DataGridView.

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

(回答第一条评论)这里我的数据表被创建为

(In Answer to First Comment) Here my DataTable is being created as

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

推荐答案

我在将 DataGridView 控件放入 TabControl 时遇到了同样的问题.

I had the same problem when I put a DataGridView control in a TabControl.

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

The DataGridView control was on the second tab of the TabControl and by default it was not shown at startup and when I switched to the second tab I encountered the issue in my implemented DataGridView_CellFormatting event.

我发现 这个来自微软:

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

"Controls contained in a TabPage are not created until the tab page is shown, and any data bindings in these controls are not activated until the tab page is shown."

我通过向 Form_Load 事件添加以下代码行解决了我的问题:

I fixed my issue by adding the following line of code to my Form_Load event:

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

这篇关于DataTable 和(数据绑定)DataGridview 中的列数不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆