Mar*_*tin 19 c# sorting entity-framework datagridview winforms
我有一个DataGridView与a相关联的BindingSource.
我BindingSource链接到一个IQueryable实体列表:
public void BindTo(IQueryable elements)
{
BindingSource source = new BindingSource();
source.DataSource = elements;
bindingNavigator1.BindingSource = source;
dataGridView1.DataSource = source;
}
Run Code Online (Sandbox Code Playgroud)
我希望我的用户能够单击网格标题来对数据进行排序 - 努力使其工作.可能吗?如果是这样,我该怎么办?
小智 12
我最近在同样的问题上苦苦挣扎; 似乎IQueryable接口没有为DataViewGrid提供足够的信息来知道如何自动排序数据; 所以你必须使用它可以使用的东西或者我做的东西从Entity源重新打包你的集合并手动处理排序功能:
private void myDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn column = myDataGridView.Columns[e.ColumnIndex];
_isSortAscending = (_sortColumn == null || _isSortAscending == false);
string direction = _isSortAscending ? "ASC" : "DESC";
myBindingSource.DataSource = _context.MyEntities.OrderBy(
string.Format("it.{0} {1}", column.DataPropertyName, direction)).ToList();
if (_sortColumn != null) _sortColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
column.HeaderCell.SortGlyphDirection = _isSortAscending ? SortOrder.Ascending : SortOrder.Descending;
_sortColumn = column;
}
Run Code Online (Sandbox Code Playgroud)
我希望有所帮助.