8

如本文所述,我有一个DataGridView由 a 支持的。SortableBindingList

这本质上是一个BindingList其数据源是自定义对象列表。底层自定义对象以编程方式更新。

SortableBindingList允许我按升序或降序对每一列进行排序。我通过重载ApplySortCore方法 来做到这一点

protected override void ApplySortCore(PropertyDescriptor prop,
                                      ListSortDirection direction)

这适用于单击列标题时的排序,但当以编程方式更新该列中的单元格时不会自动排序。

有没有其他人想出一个很好的解决方案来保持DataGridView对其底层数据源的编程更新的排序?

4

2 回答 2

4

尝试覆盖 OnDataSourceChanged 事件

public class MyGrid : DataGridView {
    protected override void OnDataSourceChanged(EventArgs e)
    {
        base.OnDataSourceChanged(e);
        MyComparer YourComparer = null;
        this.Sort(YourComparer);
    }
}
于 2013-05-29T05:51:27.963 回答
1

考虑这个类:

public class MyClass : INotifyPropertyChanged
{
    private int _id;
    private string _value;

    public int Id
    {
        get
        {
            return _id;
        }
        set
        {
            PropertyChanged(this, new PropertyChangedEventArgs("Id"));
            _id = value;
        }
    }
    public string Value
    {
        get
        {
            return _value;
        }
        set
        {
            PropertyChanged(this, new PropertyChangedEventArgs("Value"));
            _value = value;
        }
    }
    public event PropertyChangedEventHandler PropertyChanged = new PropertyChangedEventHandler(OnPropertyChanged);

    private static void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        // optional code logic
    }
}

将这些方法添加到您的可排序绑定列表中:

public class SortableBindingList<T> : BindingList<T>, INotifyPropertyChanged
    where T : class
{
    public void Add(INotifyPropertyChanged item)
    {
        item.PropertyChanged += item_PropertyChanged;
        base.Add((T)item);
    }

    void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        this.PropertyChanged(sender, new PropertyChangedEventArgs(String.Format("{0}:{1}", sender, e)));
    }

    // other content in the method body
}

并在您的表单中使用此示例方法:

public Form1()
{
    InitializeComponent();
    source = new SortableBindingList<MyClass>();
    source.Add(new MyClass() { Id = 1, Value = "one test" });
    source.Add(new MyClass() { Id = 2, Value = "second test" });
    source.Add(new MyClass() { Id = 3, Value = "another test" });
    source.PropertyChanged += source_PropertyChanged;
    dataGridView1.DataSource = source;

}

void source_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    MessageBox.Show(e.PropertyName);
    dataGridView1.DataSource = source;
}

private void button1_Click(object sender, EventArgs e)
{
    ((MyClass)source[0]).Id++;
}
于 2013-06-04T13:11:47.660 回答