以编程方式绑定数据后,C#winforms gridview排序

时间:2014-01-29 07:27:44

标签: c# winforms gridview datagridview gridview-sorting

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columnheadermouseclick(v=vs.110).aspx

private void dataGridView1_ColumnHeaderMouseClick(
    object sender, DataGridViewCellMouseEventArgs e)
{
    ...
    // Sort the selected column.
    dataGridView1.Sort(newColumn, direction);
    newColumn.HeaderCell.SortGlyphDirection =
        direction == ListSortDirection.Ascending ?
        SortOrder.Ascending : SortOrder.Descending;
}

public CustomersListWrapper(DataGridView gridView)
{
    _gridView = gridView;
    _gridView.CellClick += dgwCustomersList_CellContentClick;
    _gridView.ColumnHeaderMouseClick += dgwCustomersList_ColumnHeaderMouseClick;

    ClearGrid();
    SetCustomersListHeader();
    ....

}

private void ClearGrid()
{
    _gridView.Rows.Clear();
    _gridView.Columns.Clear();
}

private void SetCustomersListHeader()
{
    _gridView.Columns.Add(DataGridViewColumnNames.Customers.ID, "Id");
    _gridView.Columns.Add(DataGridViewColumnNames.Customers.NAME, "Ime");
    _gridView.Columns[1].Width = 360;
    _gridView.Columns.Add(DataGridViewColumnNames.Customers.SURNAME, "Priimek");
    _gridView.Columns[2].Width = 360;
    _gridView.Columns.Add(DataGridViewColumnNames.Customers.ACCOUNT_NUMBER, "Št. računa");
    _gridView.Columns[3].Width = 120;
    _gridView.Columns.Add(DataGridViewColumnNames.Customers.CUSTOMER_NUMBER, "Št. stranke");
    _gridView.Columns[4].Width = 120;

    int nLastColumn = _gridView.Columns.Count - 1;
    for (int i = 0; i < _gridView.Columns.Count; i++)
    {
        if (nLastColumn == i)
        {
            _gridView.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
    }
    ...
}

但问题是排序不起作用它始终是升序。我每次动态地将新数据绑定到网格时都会绑定,看起来这样会重置网格排序,

newColumn.HeaderCell.SortGlyphDirection

具有正确的值但在绑定后数据数据丢失且SortGlyphDirection再次为无。

我可以以某种方式记住绑定后gridview的列的值吗?

2 个答案:

答案 0 :(得分:0)

我想你是从DataTable绑定数据源吗?更改数据源会重置先前的排序,我认为有更多方法可以解决此问题:

  - 将最后使用的排序顺序存储在变量中,并使用DataGridView.DataSourceChanged或DataGridView.DataBindingComplete事件对新数据源进行排序并刷新网格

  - 存储上次使用的排序顺序,在附加新数据源之前,将源DataTable排序到DataGridView中使用的排序顺序,并在此之后更改数据源

答案 1 :(得分:0)

您必须在数据源上继承IBindingList。在Databind。

以这种方式循环和绑定相反,在我看来更容易。

        dg_Transactions.Columns.Add("1", "Date");
        dg_Transactions.Columns.Add("2", "Amount");
        dg_Transactions.Columns.Add("3", "Description");

        foreach (var row in data.Transactions)
        {
            var n = dg_Transactions.Rows.Add();

            var i = 0;
            dg_Transactions.Rows[n].Cells[i++].Value = row.Date;;
            dg_Transactions.Rows[n].Cells[i++].Value = row.Amount;
            dg_Transactions.Rows[n].Cells[i++].Value = row.Description;
        }