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

时间:2014-07-23 15:44:07

标签: c# datagridview

我在datagridview中为我的表中的特定行添加了列。通过使用此代码在sql中选择命令

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

数据网格按顺序显示列 Apple-City | Apple-Country | Banana-City | Banana-Country
我需要的是 Apple-City | Banana-City | Apple-Country | Banana-Country
如何对Datagrid中的第一行(标题)进行排序

1 个答案:

答案 0 :(得分:0)

您可以简单地遍历列两次,如下所示:

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");

请注意,OrderBy是Linq方法,因此您必须使用C#3.0或更高版本才能使用它并添加linq引用。另外,也许你应该考虑使用Entity框架。