Problem
This was particularly annoying. If you have a DataGridView you are working with, you have setup the DataGridView through the designer and you have set the DataSource once. Then you set the DataSource a second time because the data has changed – all of a sudden you lose all of your formatting and the column names are all wrong.

Solution
As stupid as this sounds, set the DataGridView’s AutoGenerateColumns property to False!
DataGridView.AutoGenerateColumns = false; //C#
DataGridView.AutoGenerateColumns = False; ‘VB.Net

There – goddamn annoying vague problem solved!

More Banter
This makes sense for this to happen, but it is still annoying. Basically what is happening is that the list of objects are being loaded into the DataGridView and overriding the existing formatting. Something similar happens in ASP.Net which is that all the predefined columns are loaded in addition to the columns from the list of objects. Windows Forms just happens to only respect the list of objects and won’t show your predefined columns… that part is silly and not so obvious.

One Reply to “DataGridView Loses Formatting and Columns After Setting DataSource a Second Time”

Leave a Reply

Your email address will not be published. Required fields are marked *