Recently I needed to specify the order that columns were supposed to show up in a datagridview. Normally, one could do this by just changing their SQL query to return the fields in the order that the user wanted to see them. But in my case, this wouldn’t work. You see, I was adding columns to the the gridview because I wanted calendar columns instead of plain text columns containing a date and I also wanted dropdown lists for some of the columns. So even though I could write my query with the columns in the right order I changed the order when I added the new columns (because I had to remove the old column that was formatted in the default way and add the new properly formatted column).
So what to do to get the columns to show up in the order I wanted? Well, just tell it what order you want them to show up in… duh.
.AutoGenerateColumns = False
.Columns(“RBD_Key”).DisplayIndex = 0
.Columns(“RBD_Carrier”).DisplayIndex = 1
.Columns(“Service”).DisplayIndex = 2
.Columns(“CountryCode”).DisplayIndex = 3
‘Just for kicks make one invisible
.Columns(“RBD_Record_Status”).Visible = False
You will see that there is a secret to it. I never even knew that the AutoGenerateColumns property existed in the windows forms world. [Note: it has a default value of true]. I use it all the time in asp.net, but never have I used it on the windows forms side… until now. Without setting ‘AutoGenerateColumns = false’ first setting those displayIndex values just doesn’t seem to work. Without setting that property first it seems to “sort of” works in that some of the columns are reordered to what you intended but some are not (which is worse than just not working at all) and will just confuse you to no end. It might work fine without setting that property, but if you did any manual column adding / removing forget about it… you have no hope without setting that property as specified. Just use it as I described and you should get the results you are looking for.
As for my sources, I did many google searches and found questions regarding this topic all over the place, but the most useful thread was this one.