简体   繁体   English

在datagridview c#中对列标题进行排序

[英]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 我在datagridview中为表中的特定行添加列。通过在sql中选择命令,使用此代码

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 数据网格按顺序显示列Apple-City | Apple-Country | Banana-City | Banana-Country
MY need is Apple-City|Banana-City|Apple-Country|Banana-Country 我需要的是Apple-City | Banana-City | Apple-Country | Banana-Country
How can i sort the first row(Headers)in Datagrid 我如何排序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. 请注意,OrderBy是Linq方法,因此您必须使用C#3.0或更高版本才能使其正常工作,并添加linq引用。 Also, maybe you should consider using the Entity framework. 另外,也许您应该考虑使用实体框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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