简体   繁体   English

如何在C#中显示和排序列表?

[英]How do I display and sort a List in C#?

I have a List of "StudentRecords" which contain students and their test scores. 我有一份“StudentRecords”列表,其中包含学生及其考试成绩。 For each student, I have their names, age, contact phone number, test scores, and the dates they took a test. 对于每个学生,我都有他们的姓名,年龄,联系电话,考试成绩以及参加考试的日期。

public class StudentRecord
{
       public String Name  { get; set; }
       public int Age  { get; set; }
       public String PhoneNum  { get; set; }
       public int TestScore1  { get; set; }
       public DateTime TestScore1Date  { get; set; }
}

List<StudentRecord> StudentList = new List<StudentRecord>();
dataGridView1.DataSource = StudentList;

I binded my List to a DataGridView control and am able to view the information just great. 我将我的List绑定到DataGridView控件,并且能够很好地查看信息。 Now, I want to be able to sort the contents of the List by things like Name first, then scores, then age within the DataGrid control. 现在,我希望能够通过名称首先排序列表的内容,然后分数,然后在DataGrid控件中对年龄进行排序。

I found this: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadermouseclick.aspx 我发现了这个: http//msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadermouseclick.aspx

which says the default behavior is to order the grid rows based on the clicked column header. 它表示默认行为是根据单击的列标题对网格行进行排序。 However, this does not happen by default when I click. 但是,单击时默认情况下不会发生这种情况。 In fact, nothing happens when I click on the column header. 事实上,当我点击列标题时没有任何反应。 Any idea what I might be doing wrong? 知道我可能做错了什么吗?

Unfortunately, this behavior is not available out-of-the-box with the DataGridView control. 不幸的是, DataGridView控件无法立即使用此行为。 In order to use List<T> as the binding source and allow for column click sorting, then you need to handle the ColumnHeaderMouseClick event of the DataGridView , like this: 为了使用List<T>作为绑定源并允许列单击排序,您需要处理DataGridViewColumnHeaderMouseClick事件,如下所示:

protected void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    // Get the information about the column clicked
    var strColumnName = dataGridView1.Columns[e.ColumnIndex].Name;
    SortOrder strSortOrder = getSortOrder(e.ColumnIndex);

    // Sort the list
    StudentList.Sort(new StudentComparer(strColumnName, strSortOrder));

    // Rebind to use sorted list
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = StudentList;

    // Update user interface icon for sort order in column clicked
    dataGridView1.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = strSortOrder;
}

private SortOrder getSortOrder(int columnIndex)
{
    if (dataGridView1.Columns[columnIndex].HeaderCell.SortGlyphDirection == SortOrder.None ||
        dataGridView1.Columns[columnIndex].HeaderCell.SortGlyphDirection == SortOrder.Descending)
    {
        dataGridView1.Columns[columnIndex].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
        return SortOrder.Ascending;
    }
    else
    {
        dataGridView1.Columns[columnIndex].HeaderCell.SortGlyphDirection = SortOrder.Descending;
        return SortOrder.Descending;
    }
}

public class StudentComparer : IComparer<StudentRecord>
{
    string memberName = String.Empty;
    SortOrder sortOrder = SortOrder.None;

    public StudentComparer(string strMemberName, SortOrder sortingOrder)
    {
        memberName = strMemberName;
        sortOrder = sortingOrder;
    }

    public int Compare(StudentRecord student1, StudentRecord student2)
    {
        int returnValue = 1;
        switch (memberName)
        {
            case "Name" :
                if (sortOrder == SortOrder.Ascending)
                {
                    returnValue = student1.Name.CompareTo(student2.Name);
                }
                else
                {
                    returnValue = student2.Name.CompareTo(student1.Name);
                }
                break;
            case "Age":
                if (sortOrder == SortOrder.Ascending)
                {
                    returnValue = student1.Age.CompareTo(student2.Age);
                }
                else
                {
                    returnValue = student2.Age.CompareTo(student1.Age);
                }
                break;
            case "PhoneNum":
                if (sortOrder == SortOrder.Ascending)
                {
                    returnValue = student1.PhoneNum.CompareTo(student2.PhoneNum);
                }
                else
                {
                    returnValue = student2.PhoneNum.CompareTo(student1.PhoneNum);
                }
                break;
            case "TestScore1":
                if (sortOrder == SortOrder.Ascending)
                {
                    returnValue = student1.TestScore1.CompareTo(student2.TestScore1);
                }
                else
                {
                    returnValue = student2.TestScore1.CompareTo(student1.TestScore1);
                }
                break;
            case "TestScore1Date":
                if (sortOrder == SortOrder.Ascending)
                {
                    returnValue = student1.TestScore1Date.CompareTo(student2.TestScore1Date;
                }
                else
                {
                    returnValue = student2.TestScore1Date.CompareTo(student1.TestScore1Date);
                }
                break;
            default:
                if (sortOrder == SortOrder.Ascending)
                {
                    returnValue = Student1.Name.CompareTo(Student2.Name);
                }
                else
                {
                    returnValue = Student2.Name.CompareTo(Student1.Name);
                }
                break;
        }
        return returnValue;
    }
}

Note: The default sorting criteria is Name . 注意:默认排序条件是Name

You must implement a custom code to datagrid can sort the data. 您必须实现自定义代码才能对datagrid进行数据排序。 means of that document about default behavior is that when you double click the grid in design mode, VS generate a method to handle this event. 该文档关于默认行为的方法是,当您在设计模式下双击网格时,VS会生成一个方法来处理此事件。 read this : Sort DataGrid 阅读本文: 对DataGrid进行排序

First I think you need to implement that behavior, I doubt it's out of the box. 首先,我认为你需要实现这种行为,我怀疑它是开箱即用的。

Second, you could easily sort your objects using LINQ , and have nice groups etc. 其次,您可以使用LINQ轻松地对对象进行排序,并拥有不错的组等。

Now, if you would like to sort them by different criteria according to clicks, you might need to go with a ListView, and then you would be able to have filters on that, but this is usually a bit longer to do. 现在,如果您希望根据点击次数按照不同的标准对它们进行排序,您可能需要使用ListView,然后您就可以对其进行过滤,但这通常需要更长的时间。 Here's the MSDN page and at the bottom you have a link to how to sort on header clicked ... 这是MSDN页面 ,在底部你有一个链接到如何排序点击标题...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将列表中的人分类成组? C# - How do i sort people from a list into groups? C# 如何在c#中对动态列表进行排序 - How do I sort the dynamic list in c# 如何将列表显示到C#Datagrid中? - How do I display my List into a C# Datagrid? 如何在C#中对数组排序? - how do I sort an array in C#? 如何使用C#在列表视图列的标题中显示排序箭头? - How to I display a sort arrow in the header of a list view column using C#? 如何在 while 循环中对克隆的临时列表进行排序而不对原始列表 (C#) 进行排序? - How do I sort a cloned temp list in a while loop without also sorting the original list(C#)? 如何以编程方式对 C# SQL Server 数据库进行排序并将每个项目显示为单独的按钮? - How do I sort a C# SQL Server database programmatically and display each item as a separate button? 如何根据C#.NET Silverlight中Dictionary中的键值对字典列表进行排序? - How do I sort a List of Dictionaries based off of a value in a key within the Dictionary in C# .NET Silverlight? 如何按 c# 列表中的 object 中的字段排序? - How do I sort by a field inside an object inside a list in c#? C#:如何按特定参数对对象的数组列表进行排序? - C#: How do I sort an array list of objects by a specific parameter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM