user1662290 user1662290 - 5 months ago 31
C# Question

C# DataGridView Column Order

In my application, I have a DataGridView which it's data source varies depening on the button you click.
E.G. Clicking 'Total Downloads' it will be:

dataGridView1.DataSource = totalDownloads();

Or the downloads per player

dataGridView1.DataSource = playerDownloads();

Each method obtains data via SQL query and returns a dataTable of this information.

However, with my following code:

public DataTable getStats()
DataTable table1 = new DataTable("Totals");
table1.Columns.Add("Park Name");
table1.Columns.Add("Total Downloads");
table1.Columns[2].DataType = typeof(int);
table1.Columns.Add("Rating (Max 5)");
table1.Columns[3].DataType = typeof(float);
table1.Rows.Add(name,author,download, rating);
return table1;

I expected to see the colums in the order: "Park Name" "Author" "Total Downloads" "Rating"
However, they come in "Downloads", "Park Name", "Author", "Rating"

I've read that adding: dataGridView1.AutoGenerateColumns = false;
will fix this...however, this makes no difference to the order at all...

thanks for the help!


Is this a WinForms project or an one?

If it's winforms you should be able to change the order the columns are displayed in by accessing your GridViews Columns DisplayIndex

    dataGridView1.Columns["Park Name"].DisplayIndex = 0; // or 1, 2, 3 etc