我的数据有几列:例如Brand、Colour、Power、ReleaseYear。因此,当用户单击Datagrid的列标题时,Datagrid的自动功能会自动对数据进行排序。尽管如此,我想立即应用按 ReleaseYear 进行的第二次排序,与单击的标题无关。有没有办法添加这种排序,例如 通过处理排序事件?
在 C# 中,特别是在使用 DataGridView 或 DataGrid(对于 WPF 应用程序)时,您可以通过挂钩排序事件并修改排序逻辑来处理排序并应用二次排序。以下是如何为 WinForms (DataGridView) 和 WPF (DataGrid) 实现此目的。
以下是如何实现它的示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
public partial class MainForm : Form
{
private List<Product> products;
public MainForm()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
products = new List<Product>
{
new Product { Brand = "Apple", Colour = "Red", Power = "500W", ReleaseYear = 2020 },
new Product { Brand = "Samsung", Colour = "Blue", Power = "600W", ReleaseYear = 2021 },
new Product { Brand = "LG", Colour = "Green", Power = "700W", ReleaseYear = 2019 },
// Add more products here...
};
dataGridView1.DataSource = products;
}
private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
// First, sort by the clicked column
string sortColumn = dataGridView1.Columns[e.ColumnIndex].DataPropertyName;
// Determine if the column is already sorted ascending or descending
ListSortDirection sortDirection = ListSortDirection.Ascending;
if (dataGridView1.SortOrder == SortOrder.Ascending)
{
sortDirection = ListSortDirection.Descending;
}
// Apply primary sorting based on the clicked column
var sortedList = SortByColumn(products, sortColumn, sortDirection);
// Apply secondary sorting by ReleaseYear (ascending)
var secondarySortedList = sortedList.OrderBy(p => p.ReleaseYear).ToList();
// Update the DataGridView with the newly sorted data
dataGridView1.DataSource = secondarySortedList;
}
private List<Product> SortByColumn(List<Product> data, string column, ListSortDirection direction)
{
switch (column)
{
case "Brand":
return direction == ListSortDirection.Ascending ?
data.OrderBy(p => p.Brand).ToList() :
data.OrderByDescending(p => p.Brand).ToList();
case "Colour":
return direction == ListSortDirection.Ascending ?
data.OrderBy(p => p.Colour).ToList() :
data.OrderByDescending(p => p.Colour).ToList();
case "Power":
return direction == ListSortDirection.Ascending ?
data.OrderBy(p => p.Power).ToList() :
data.OrderByDescending(p => p.Power).ToList();
case "ReleaseYear":
return direction == ListSortDirection.Ascending ?
data.OrderBy(p => p.ReleaseYear).ToList() :
data.OrderByDescending(p => p.ReleaseYear).ToList();
default:
return data;
}
}
}
public class Product
{
public string Brand { get; set; }
public string Colour { get; set; }
public string Power { get; set; }
public int ReleaseYear { get; set; }
}
说明: