我在C#中遇到DataGridView的问题。
案例是:
我在数据库上做了一些更新,然后用新值重新加载DataGridView:
myDataGridView.DataSource = myDataSet.Tables[0]
一切都还可以,但最近我被问到是否有可能在重新加载数据后保持应用相同的列过滤?
做这个过滤案例的方法是什么?
感谢任何想法。
答案 0 :(得分:14)
好的,我找到了解决方案,也许它会对某人有所帮助: [顺便说一句。我做了一些语言错误过滤=排序; - )]
DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
ListSortDirection direction;
if (dataGridView1.SortOrder == SortOrder.Ascending) direction = ListSortDirection.Ascending;
else direction = ListSortDirection.Descending;
databaseUpdateFunction();
DataGridViewColumn newColumn = dataGridView1.Columns[oldColumn.Name.ToString()];
dataGridView1.Sort(newColumn,direction);
newColumn.HeaderCell.SortGlyphDirection =
direction == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
我使用了以下部分代码:link text
答案 1 :(得分:7)
我拿了kuba的解决方案,把它放在我可以在任何DataGridView
使用的实用程序类中:
private static ListSortDirection _oldSortOrder;
private static DataGridViewColumn _oldSortCol;
/// <summary>
/// Saves information about sorting column, to be restored later by calling RestoreSorting
/// on the same DataGridView
/// </summary>
/// <param name="grid"></param>
public static void SaveSorting(DataGridView grid)
{
_oldSortOrder = grid.SortOrder == SortOrder.Ascending ?
ListSortDirection.Ascending : ListSortDirection.Descending;
_oldSortCol = grid.SortedColumn;
}
/// <summary>
/// Restores column sorting to a datagrid. You MUST call this AFTER calling
/// SaveSorting on the same DataGridView
/// </summary>
/// <param name="grid"></param>
public static void RestoreSorting(DataGridView grid)
{
if (_oldSortCol != null)
{
DataGridViewColumn newCol = grid.Columns[_oldSortCol.Name];
grid.Sort(newCol, _oldSortOrder);
}
}
使用它看起来像:
GridUtility.SaveSorting(grid);
grid.DataSource = databaseFetch(); // or whatever
GridUtility.RestoreSorting(grid);
答案 2 :(得分:0)
在我遇到问题之前,我遇到了Adam Nofsinger的答案,但无论如何我都用过它。它很棒。
只需将这两个使用行添加到我的类文件中:
using System.ComponentModel;
using System.Windows.Forms;
谢谢, 吉尔特。
答案 3 :(得分:0)
这对我有用:
//preserve existing sort column and direction
ListSortDirection direction;
DataGridViewColumn oldsort = MyDataGridView.SortedColumn;
if (MyDataGridView.SortOrder == SortOrder.Ascending)
{ direction = ListSortDirection.Ascending; } else { direction = ListSortDirection.Descending; }
//this is refresh
MyDataGridView.DataSource = data;
//reapply sort and direction
if (oldsort != null) { MyDataGridView.Sort(MyDataGridView.Columns[oldsort.Name], direction); }