【问题标题】:Sort direction does not work in datagridview排序方向在 datagridview 中不起作用
【发布时间】:2013-07-14 14:47:02
【问题描述】:

我创建了一个数据网格视图并将每列的排序模式属性设置为自动。然后,我将 datagridview 与列表绑定,并尝试按升序或降序排序,但对我的 datagridview 列都不起作用。

我的示例代码如下。

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PBAttendance
{
    public partial class frmFormTest : Form
    {
        public frmFormTest()
        {
            InitializeComponent();
        }

        private void frmFormTest_Load(object sender, EventArgs e)
        {
            tempDataList tmplist = new tempDataList();
            for(int i=0; i<10; i++)
            {
                tempData tmp = new  tempData();
                tmp.Name=i.ToString();
                tmplist.Add(tmp);
            }


            dataGridView1.Columns[0].DataPropertyName = "Name";
            BindingSource bs = new BindingSource();
            bs.DataSource = tmplist;
            dataGridView1.DataSource = bs;
        }
    }
    public class tempData
    {
        string name = null;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

    }
    public class tempDataList : List<tempData>
    {
    }
}

【问题讨论】:

  • 通常“自动”意味着你不能改变它。
  • 当我使用通用列表绑定数据网格视图时,@banging 列标题中的向上和向下箭头不会出现。如果我使用普通列表或通常将内容添加到单元格中,则它是可见的,并且信息也已排序
  • 在这种情况下,自动排序没有任何意义。你必须选择 asc 或 desc,或者什么都没有。不要在 dataGrid 上添加排序,您可以通过单击列对其进行排序。

标签: c# datagridview


【解决方案1】:

默认情况下,List 在绑定到 DataGridView (DGV) 时不支持排序。有关可行的解决方案,请参阅How do I implement automatic sorting of DataGridView?。我的是使用BindingListView library,让代码像bs.DataSource = new BindingListView&lt;tempData&gt;(tmplist);一样简单。

只是对样式和语法的补充说明,因为看起来您已经习惯了 Java,并且存在一些差异:

  • 类名是 PascalCase(例如 TempDataList,尽管在您提供的 sn-p 中,仅使用 var tmplist = new List&lt;tempData&gt;() 没有任何缺点)
  • 局部变量可以是任何形式,但通常是驼峰式(例如 tmpList,尽管使用 Visual Studio 的智能感知,没有理由在变量名称中包含类型)。
  • 子类通常附加其基类的名称,例如TestForm 而不是 frmFormTest,尽管匈牙利符号 (frmTest) 在扩展基类库的文件名和类上仍有一些优势。 (但在大多数情况下,这些优势并没有扩展到变量名:使用 bool isFormValidated 比使用 bool bValid 更好。)
  • 关于properties,尤其是auto-properties,不需要后备字段,只需public string Name {get; set;}strings 的默认值为null)。如果您需要默认值,请使用 readonly property (public string Name {get; private set;}) 并在构造函数中设置其值,否则您可以使用支持字段。

我并没有指出这些是个混蛋(如果我冒犯了我很抱歉);几年前这些对我来说是有用的指针,也许还不熟悉 C# 的其他人会发现它们很有用。另外,请注意style can be automatically checked(并且已修复,例如使用 ReSharper 或 CodeRush)。

最后,.net 上最好的书,尤其是对于中级程序员,是 Cwalina 和 Abrams 的Framework Design Guidelines(无论您是否正在设计框架)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2011-06-11
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    相关资源
    最近更新 更多