在datagridviewc#中排序列标题



我在datagridview中为表中的特定行添加列。通过sql中的select命令。使用以下代码

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

数据网格按顺序列示苹果城|苹果国|香蕉城|香蕉国
我的需要是苹果城|香蕉城|苹果国|香蕉国
我如何排序第一行(标题)在Datagrid

您可以简单地对列进行两次迭代,如下所示:

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引用。此外,也许你应该考虑使用实体框架。

最新更新