I’m working with a DataGridView, and ran into a problem where the columns are sometimes not displayed in the correct order according to the DisplayIndex. I found a mention of the same problem on a different site, http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/35c1ed09-f4a4-4b3d-bd46-35a11cb8a9bc .
The problem seems to be when a column doesn’t show up on the initial display of the grid, due to being off to the right and requiring scrolling to see it. When the columns are few enough that all of them will be seen without scrolling, then the order is correct. If a column is added so that one of the columns will require scrolling to see it, then the column that is to the right will not be the last column according to the DisplayIndex, it will be a column that was supposed to be shown earlier.
While I could try and change the logic in my window to work similarly to the suggestion in the link above, I don’t like that the base problem is just glossed over and a work-around is required. Does anyone else have any suggestions as to how to address this problem in a way that addresses the problem itself instead of a work-around?
Here’s a code snippet of how I’m currently doing the ordering:
// Fill the data grid view with data from the database.
dataGridView1.DataSource = null;
DataTable dt = // Logic to get data from DB here
dataGridView1.DataSource = dt;
// Get the column display data. This can change per user.
DataTable columnDisplay = // Logic to get data from DB here
bool foundMatch;
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
foundMatch = false;
foreach (DataRow row in columnDisplay.Rows)
{
if (row["column_name"].ToString().Equals(column.Name, StringComparison.CurrentCultureIgnoreCase))
{
foundMatch = true;
if (row["show_in_window"].ToString().Equals("y"))
{
// Set the column placement and display name.
dataGridView1.Columns[column.Name].DisplayIndex = Convert.ToInt32(row["column_sequence"].ToString());
dataGridView1.Columns[column.Name].HeaderText = row["display_name"].ToString();
dataGridView1.Columns[column.Name].Width = 105;
}
else
{
// Hide the column.
dataGridView1.Columns[column.Name].Visible = false;
}
break;
}
}
// If the column is not in the display table, then it should not be displayed at all.
if (!foundMatch)
column.Visible = false;
}
Alright, since no one has responded, I’ll give an update — I did not take the time to resolve this issue. It’s deemed a low enough priority that I may not get to it for months, if at all.
One interesting piece of information that I found since the original post is that when modifying the display index number for a column, the rest of the columns are automatically changed to account for it. That was not obvious to me when I read the msdn documentation, so maybe it will be helpful for anyone else stumbling across this.