Reputation: 249
I have 3 datagridviews, and each of them has a separate binding source. All three binding sources however get data from the same datatable.
bindingSource1.DataSource = mytable;
bindingSource2.DataSource = mytable;
bindingSource3.DataSource = mytable;
dataGridView1.DataSource = bindingSource1;
dataGridView2.DataSource = bindingSource2;
dataGridView3.DataSource = bindingSource3;
I control what the user sees with the following logic: Show 10 first columns on the first grid, the next 10 on the second, and the next 10 on the third.
for (int i = 0; i < mytable.Columns.Count; i++)
{
dataGridView1.Columns[i].Visible = i < 10;
dataGridView2.Columns[i].Visible = (i >= 10 && i < 20);
dataGridView3.Columns[i].Visible = (i >= 20 && i < 30);
}
This works fine when I have many columns in the datatable.
Problem If I have less than 10 columns in my datatable, normally they should only be shown in the first datagridview. This does happen, but also the first column of the datatable is always shown in datagrid 2 and 3. I have stepped through my loop to see whether a condition is wrong, and I found it to be correct. Therefore, I am pretty sure it must be one of the events that follow this. I have two events registed for my grids that could be the cuplrits: RowPostPaint and CellPainting. I commented out everything that I was doing in these events and still get this problem. I also have some others, like DataError, CellValueChanged(empty inside), Scroll etc, but I think they are irrelevant.
So I am wondering whether there is another event which I haven't registered, which could be doing this by itself.
Upvotes: 1
Views: 107
Reputation: 5454
You're seeing this behavior because of a default behavior that happens when binding the data source. To fix, handle each DataGridView.DataBindingComplete
event. We will use the same event handler for each:
dataGridView1.DataBindingComplete += DataGridView_DataBindingComplete;
dataGridView2.DataBindingComplete += DataGridView_DataBindingComplete;
dataGridView3.DataBindingComplete += DataGridView_DataBindingComplete;
In that event handler, we will set the visible columns as before. But we will also set the row headers' visibility as well as scroll bars - in case no columns are visible.
private void DataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridView view = sender as DataGridView;
bool anyVisible = false;
int max = 0, min = 0;
if (view == this.dataGridView1)
{
min = 0;
max = 10;
}
else if (view == this.dataGridView2)
{
min = 10;
max = 20;
}
else if (view == this.dataGridView3)
{
min = 20;
max = 30;
}
for (int i = 0; i < this.table.Columns.Count; i++)
{
view.Columns[i].Visible = i >= min && i < max;
anyVisible = anyVisible || view.Columns[i].Visible;
}
view.RowHeadersVisible = anyVisible;
view.ScrollBars = anyVisible ? ScrollBars.Both : ScrollBars.None;
}
Upvotes: 1