public partial class Form10 : Form
{
private BindingList
public Form10()
{
InitializeComponent();
InitializeData();
InitializeDataGridView();
}
private void InitializeData()
{
// 创建一个List作为数据源
List
{
new MyData { Property1 = "Value1", Property2 = 42 },
new MyData { Property1 = "Value2", Property2 = 20 }
};
// 创建一个BindingList并将数据复制到其中
bindingList = new BindingList
}
private void InitializeDataGridView()
{
// 将DataGridView绑定到BindingList
dataGridView1.DataSource = bindingList;
// 启用表头排序
dataGridView1.AutoGenerateColumns = true;
// 订阅ColumnHeaderMouseClick事件以处理排序
dataGridView1.ColumnHeaderMouseClick += DataGridView_ColumnHeaderMouseClick;
}
private void DataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn clickedColumn = dataGridView1.Columns[e.ColumnIndex];
if (clickedColumn != null)
{
// 获取当前排序状态
ListSortDirection currentDirection = GetSortDirection(clickedColumn);
// 切换排序顺序
ListSortDirection newDirection = (currentDirection == ListSortDirection.Ascending) ? ListSortDirection.Descending : ListSortDirection.Ascending;
// 执行排序
SortDataGridView(clickedColumn.DataPropertyName, newDirection);
}
}
private ListSortDirection GetSortDirection(DataGridViewColumn column)
{
if (column.HeaderCell.SortGlyphDirection == SortOrder.Ascending)
return ListSortDirection.Ascending;
else if (column.HeaderCell.SortGlyphDirection == SortOrder.Descending)
return ListSortDirection.Descending;
else
return ListSortDirection.Ascending;
}
private void SortDataGridView(string propertyName, ListSortDirection direction)
{
// 将BindingList中的数据复制到一个List中
List
// 根据排序方向和属性名称进行排序
if (direction == ListSortDirection.Ascending)
listCopy.Sort((x, y) => Comparer.Default.Compare(GetPropertyValue(x, propertyName), GetPropertyValue(y, propertyName)));
else
listCopy.Sort((x, y) => Comparer.Default.Compare(GetPropertyValue(y, propertyName), GetPropertyValue(x, propertyName)));
// 清空BindingList并将排序后的数据添加回去
bindingList.Clear();
foreach (var item in listCopy)
{
bindingList.Add(item);
}
// 更新排序图标
if (direction == ListSortDirection.Ascending)
dataGridView1.Columns[propertyName].HeaderCell.SortGlyphDirection = SortOrder.Ascending;
else
dataGridView1.Columns[propertyName].HeaderCell.SortGlyphDirection = SortOrder.Descending;
}
private object GetPropertyValue(MyData item, string propertyName)
{
// 使用反射获取属性值
var propertyInfo = typeof(MyData).GetProperty(propertyName);
if (propertyInfo != null)
{
return propertyInfo.GetValue(item, null);
}
return null;
}
}
public class MyData
{
public string Property1 { get; set; }
public int Property2 { get; set; }
}