按列名称对网格视图进行排序

本文关键字:视图 排序 网格 | 更新日期: 2023-09-27 18:31:31

我正在制作一个GridView并将其分配给ListView的View属性。ListViewItemsSource绑定到ObservableCollection<Entry>Entry是我的 MVVM 应用程序中的一个模型,它包含一个List<KeyValuePair<string,string>> 。它还有一个索引器,用于获取与索引器参数匹配的第一个KeyValurPair<string,string>Value属性(从列表中)。所以它很像字典。

现在,这就是我制作 GridView 的方法。

foreach (Column column in category.Columns.Where(c => c.IsVisibleInTable)) {
    var gridViewColumn = new GridViewColumn {
                                                Header = column.Name,
                                                DisplayMemberBinding = new Binding($"[{column.Name}].Value")
                                            };
    gridView.Columns.Add(gridViewColumn);
}

Column也是一个模型,但这在这里并不真正相关。

现在,我想告诉 GridView 根据第一列进行排序。但是我不能使用ItemsSource的 DefaultView 并向其添加SortDescription,因为SortDescription需要一个属性名称,而我没有绑定到属性名称,而是绑定到索引器。
那么如何根据第二列进行排序呢?

按列名称对网格视图进行排序

这里是排序算法

iN 网格视图传递这两个参数 aspx AllowSorting="true" OnSorting="OnSorting"

private string SortDirection { get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; } set { ViewState["SortDirection"] = value; } } protected void OnSorting(object sender, GridViewSortEventArgs e) { this.BindGrid(e.SortExpression); }

在这里我们必须放置代码' private void BindGrid(string sortExpression = null) { 控制室。打开();

        SqlCommand cmd = new SqlCommand("SELECT * from [test].[dbo].[myform] order by name", conn);
        SqlDataAdapter sda = new SqlDataAdapter();
        cmd.Connection = conn;
        sda.SelectCommand = cmd;
        using (DataTable dt = new DataTable())
        {
            sda.Fill(dt);
            if (sortExpression != null)
            {
                DataView dv = dt.AsDataView();
                this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";
                dv.Sort = sortExpression + " " + this.SortDirection;
                GridView2.DataSource = dv;
            }
            else
            {
                GridView2.DataSource = dt;
            }
            GridView2.DataBind();
            conn.Close();
        }
    }`