This is what I do because the columns are added at run time via the users preference.
I am using a listView to display information from a database to the user. ( I probably should use DataGrid, but when I first made the program DataGrid didn't have built in full row select and I was too big of a newb to go through the custom control examples I found)
The user selects which columns they want to show up out of the total, how wide, and the title text.
I created a user preferences table that saved information about the columns to add
- ColumnVisible = bool
- ColumnText = string = text to display in header
- columnWidth = int
- ColumName = string = the exact name this column will refer to in my other database
- ColumnIndex = int = the display index of the column
I also made a class ColumnPreferences and added a property for each of those columns
Used DataReader to make List<ColumnPreferences>
I sort this list according to display index, so I can iterate through it in the order the columns are displayed.
I do an if statement checking if the next preference in preferences is visible.
If it is then I add the column using ListView1.Columns.Add(ColumnName, ColumnText, ColumnWidth);
At this point the columns are all set, to save where the user drags them around to I do basically the opposite. I iterate through all column in Listview.columns and save the column display index and column width back into my user preference table
When loading the actual data from the table I use this same list of column preferences to check whether I should display the data.
it is again sorted by display index, I check if it is visible, if it is not I skip it and go to the next one
if it is visible I use myDataReader[ ColumnPreference.ColumnName ] to look up the approprate ordinal for the data I want.
I just add each of those results, in order, to a list view item / subitems then add them to the list view