问题
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);
}
}
}
Call for RefreshGrid()
public Form1()
{
InitializeComponent();
myDataGridView1.RefreshGrid();
}
Please find the error and suggest me the solution.
回答1:
I found answer for this question
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.
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.
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.
回答2:
You should retrieve only columns from data table that you want to display in DataGridView.
var results = _table
.AsEnumerable()
.Where("Add your condition")
.Select("your columns names");
this.DataSource = results;
So now you don't need to remove any columns from DataGridView
回答3:
I found answer for this question
I need to call RefreshGrid() method on Form Load not on Form constructor, after calling it on Form Load my problem get solved. But I dont know why it wasnt working on Form constructor.
来源:https://stackoverflow.com/questions/18359031/why-datagridcolumn-not-getting-removed-from-datagridview