为什么 DataGridColumn 没有从 DataGridView 中删除 [英] Why DataGridColumn not getting removed from DataGridView
问题描述
我有自定义的 DataGridView
控件,在该控件中有 RefreshGrid()
方法,它使用 DataSource 填充 DataGridView
.现在我想在 DataSource 绑定后从 DataGridView
中删除几列,但无法删除那些列,当我调用 RefreshGrid()
方法然后这些列从 DataGridView
中删除.这是方法 RefreshGrid()
I have custom DataGridView
control and in that control there is RefreshGrid()
method which fill DataGridView
by using DataSource. Now I am tring to remove few columns from that DataGridView
after DataSource binding but unable to remove those, those column not getting removed but add at the end of DataGridView, when I call RefreshGrid()
method again then those column get removed from DataGridView
. Here is code for method RefreshGrid()
public void RefreshGrid()
{
DataTable _table = AccessConnectionManagers.GetDataTableBySQLQuery("select Colm1,Colm2,Colm3 from TableName");
//Data Source Binding with DataGridView
this.DataSource = _table;
if (!string.IsNullOrEmpty("Colm1"))
{
var _colmArray = GridRemoveColumnName.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries).Where(a => this.Columns.Contains(a)).Select(a => a).ToArray();
foreach (string colm in _colmArray)
{
//Remove column after Source Binding
this.Columns.Remove(colm);
}
}
}
调用RefreshGrid()
public Form1()
{
InitializeComponent();
myDataGridView1.RefreshGrid();
}
请找出错误并向我建议解决方案.
Please find the error and suggest me the solution.
推荐答案
我找到了这个问题的答案
I found answer for this question
我需要在 Form Load 而不是 Form 上调用 RefreshGrid() 方法构造函数,在 Form Log 上调用它后,我的问题得到解决.但是我不知道为什么它在 Form 构造函数上不起作用.
I need to call RefreshGrid() method on Form Load not on Form constructor, after calling it on Form Log my problem get solved. But I dont know why it wasnt working on Form constructor.
我猜您尝试访问尚不存在的列.您正在使用 DataGridView.AutoGenerateColumns
功能,即使您设置了 DataSource
属性,DatagridView
也不会在显示网格之前创建列.这就是为什么它在表单构造函数中不起作用,但在 form_Load
事件中或在显示网格之后起作用的原因.
I guess you try to access columns that do not exist yet. You are using the DataGridView.AutoGenerateColumns
functionnality and even if you set the DataSource
property, The DatagridView
won't create columns until the grid is displayed. It's why it doesn't work in form constructor, but works in form_Load
event or after that the grid has been displayed.
使用 form_Load
可能是一种可能的解决方法,但我建议您使用 DataGridView.DataBindingComplete
事件,专门用于处理这种情况.
Using form_Load
is maybe a possible workaround, but I reommand you to use the DataGridView.DataBindingComplete
event which is especially designed to handle this situation.
这篇关于为什么 DataGridColumn 没有从 DataGridView 中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!