【问题标题】:Exclude the Totals Row from sorting a bound DataGridView从排序绑定的 DataGridView 中排除总计行
【发布时间】:2014-06-18 20:40:38
【问题描述】:

我将总计行显示为最后一行。当用户单击列标题时,我想从排序中排除该行。通过使用sql union,我将总列添加到我的结果中。我正在使用 SQL、C# 和 DataGridView 控件。我无法公开ColumnHeader_Click 事件。我只使用TableStyle[0].AllowSorting = false。如何在控件上应用自定义排序?

谢谢

【问题讨论】:

  • 我会说,在您的联合中添加另一个隐藏列。所有记录将为 1,您的总计记录将为 2。然后,当您对 Dataview 进行排序时,始终先按该列排序,然后再按所有其他列排序。

标签: c# winforms .net-1.1


【解决方案1】:

感谢 TaW,您的回答帮助了我。我的需求有点不同,我需要将 Total 显示在顶部,并在整个过程中保留排序列,因为我的网格与大量过滤和所呈现数据的变化具有高度交互性。

我的排序是通过

完成的
protected void ReportGridView_Sorting(object sender, GridViewSortEventArgs e)

这是我最终在填充 GridView 的方法中使用的内容:

if (!myDataTable.Columns.Contains("SortLevel"))
{
    myDataTable.Columns.Add("SortLevel", typeof(Int16));
    foreach (DataRow dr in myDataTable.Rows)
    {
        dr["SortLevel"] = 0;
    }
    dt.Rows[0]["SortLevel"] = 1;
}

if ((Session["SortDirection"] != null) && (Session["SortExpression"] != null))
{
    myDataTable.DefaultView.Sort = "SortLevel DESC, " + Session["SortExpression"] + " " + Session["SortDirection"];
}
MyGridView.DataSource = myDataTable;
MyGridView.AllowSorting = true;
MyGridView.DataBind();

旁注:我不得不使用 Sessions 来保存自定义排序而不是 ViewState,因为这与我的 gridview 中动态创建的按钮无法正常工作

【讨论】:

    【解决方案2】:

    此解决方案基于 @T.S. 的建议,但直接在 DataSet 中工作,而不是在 SQL 中。

    我在VS2013中测试过;我不知道它是否可以在 .Net 1.1 中工作,并且必须恢复一台非常旧的机器来测试它..

    我不知道你说的是什么

    我无法公开 columnheader_click 事件。

    我已将解决方案拆分为一个函数和ColumnHeaderMouseClick 事件;如果您真的无法使用该事件,则必须找到另一种方法;但是您需要以一种或另一种方式触发排序并决定按哪一列进行排序。

    解决方案的核心是新列值的设置和用于识别“TotalsRow”的表达式。我使用了测试表的 PK 列“ID”并将“ID=1 记录”推到底部。将所有行的排序列设置为 0 后,适合表达式的第一行设置为 maxInt。

    您必须将其调整为适用于您的结果集的表达式。

    我正在添加设置动态自定义排序列,并在排序后删除它; DGV 正在暂停其布局,直到整个事件完成。

    DataTable yourTable = .. 
    
    private void dataGridView1_ColumnHeaderMouseClick(object sender, 
                                                      DataGridViewCellMouseEventArgs e)
    {
        string col = dataGridView1.Columns[e.ColumnIndex].Name;
        if (col != "") sortDGV (col );
     }
    
    private void sortDGV(string col)
    {
        dataGridView1.SuspendLayout();
        yourTable.Columns.Add("sortMe", typeof(Int32));
    
        yourTable.DefaultView.Sort = col;
    
        DataRow[] dr = yourTable.Select("ID='1'");
        for (int r = 0; r < yourTable.Rows.Count; r++) yourTable.Rows[r]["sortMe"] = 0;
        dr[0]["sortMe"] = int.MaxValue;
    
        yourTable.DefaultView.Sort = "sortMe," + col;
    
        yourTable.Columns.Remove("sortMe");
        dataGridView1.ResumeLayout();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-19
      • 2017-09-20
      • 2010-12-14
      • 1970-01-01
      相关资源
      最近更新 更多