虚拟模式为真时如何在DataGridView数据中排序

时间:2019-02-21 10:28:44

标签: c# wpf winforms

我知道,当虚拟模式启用时,我无法使用排序,这是因为 DataGridView 不是数据源,换句话说,您可以不要使用虚拟模式进行排序,因为DVG不知道排序

我的问题是我有大数据,我需要使用虚拟模式,这将有助于我快速读取所有数据。但是我不能排序了。 Hier是同一个问题,但没有帮助,因为 bound Unbound Cloumns

问题是,如何使用Virtaul-Mode进行排序。

我的代码示例:

    private List<Person> _personList;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _personList = new List<Person>();
        _personList.Add(new Person { FirstName = "Max", LastName = "Mustermann" });
        _personList.Add(new Person { FirstName = "Alex", LastName = "bhaa" });
        _personList.Add(new Person { FirstName = "jod", LastName = "dga" });

        dgv.Columns.Add("FirstName", "Vorname");
        dgv.Columns.Add("LsstName", "Nachname");
        dgv.Columns[0].SortMode = DataGridViewColumnSortMode.Automatic;
        dgv.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
        dgv.AllowUserToAddRows = true;
        dgv.Rows.Clear();
        dgv.Rows.AddCopies(0, _personList.Count);
        dgv.AllowUserToAddRows = false;
        dgv.SortCompare += Dgv_SortCompare;
    }

    private void Dgv_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        var value1 = dgv[e.Column.Index, e.RowIndex1];
        var value2 = dgv[e.Column.Index, e.RowIndex2];
        e.SortResult = string.CompareOrdinal(value1.Value.ToString(), value2.Value.ToString());
        e.Handled = true;
    }

    private void dgv_CellValueNeeded(object sender, DataGridViewCellValueEventArgs cellValueEventArgs)
    {
        int rowIndex = cellValueEventArgs.RowIndex >= _personList.Count ? -1 : cellValueEventArgs.RowIndex;
        if (rowIndex == -1)
        {
            return;
        }

        var person = _personList[cellValueEventArgs.RowIndex];
        var value = cellValueEventArgs.ColumnIndex == 0 ? person.FirstName : person.LastName;
        cellValueEventArgs.Value = value;
        dgv.Rows[rowIndex].Tag = person;
    }

    private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        dgv.VirtualMode = false;
        dgv.Sort(dgv.Columns[0], ListSortDirection.Descending);
        dgv.VirtualMode = true;
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
};

0 个答案:

没有答案