简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM