rj tubera
rj tubera

Reputation: 757

Datagridview Ordering of Column Headers- Winform C#

I have a datatable bound to a datagridview. However, the ordering of columns is messed up. I already made a column headers for each field put dataproperty name. I arranged it in the designer view. However, if i run the program column headers doesn't follow my arrangement. =_=. Does anybody know how to solve this....

EDIT:: I've Tried this approach. Is it Okay?

void SortDataGridViewColumns(DataGridView dgv)
{
    var list = from DataGridViewColumn c in dgv.Columns
               orderby c.Index
               select c;

    int i = 0;
    foreach (DataGridViewColumn c in list)
    {
        c.DisplayIndex = i++;
    }
}

***I've got this here but I use Index instead of Headertext. CASE CLOSED! LOL

Upvotes: 0

Views: 7662

Answers (1)

Jonathan
Jonathan

Reputation: 12025

I think you wil need to change the column order in runtime.

From MSDN:

When you use a DataGridView to display data from a data source, the columns in the data source's schema sometimes do not appear in the order you would like to display them. You can change the displayed order of the columns by using the DisplayIndex property of the DataGridViewColumn class.

You can change the order of the columns like this:

private void AdjustColumnOrder()
{
    customersDataGridView.Columns["CustomerID"].Visible = false;
    customersDataGridView.Columns["ContactName"].DisplayIndex = 0;
    customersDataGridView.Columns["ContactTitle"].DisplayIndex = 1;
    customersDataGridView.Columns["City"].DisplayIndex = 2;
    customersDataGridView.Columns["Country"].DisplayIndex = 3;
    customersDataGridView.Columns["CompanyName"].DisplayIndex = 4;
}

http://msdn.microsoft.com/en-us/library/wkfe535h.aspx#Y0

If you're going t use it frequently, I recomend you to make use of extension methods to add sintactic sugar and make it easy to read and maintain.

Upvotes: 7

Related Questions