简体   繁体   中英

Sort column headers in datagridview c#

I add columns in datagridview for particular row in my table.By select command in sql.using this code

foreach (DataRow rowCol in dsCol.Tables["Columns"].Rows)
{
    dt.Columns.Add(rowCol["Price"].ToString() + " - City");
    dt.Columns.Add(rowCol["Price"].ToString() + "  - Country");
}

Data Grid Shows columns in order Apple-City|Apple-Country|Banana-City|Banana-Country
MY need is Apple-City|Banana-City|Apple-Country|Banana-Country
How can i sort the first row(Headers)in Datagrid

You can simply iterate over your columns twice, like this:

foreach (DataRow rowCol in dsCol.Tables["Columns"].Rows.OrderBy(x => x["Price"].ToString()))
    dt.Columns.Add(rowCol["Price"].ToString() + " - City");

foreach (DataRow rowCol in dsCol.Tables["Columns"].Rows.OrderBy(x => x["Price"].ToString()))
   dt.Columns.Add(rowCol["Price"].ToString() + "  - Country");

Please note that the OrderBy is a Linq methods, so you have to be using C# 3.0 or newer for this to work and also add the linq references. Also, maybe you should consider using the Entity framework.

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