我的winForm应用程序中有一个datagridview,它链接到实体模型。这是在datagridview中加载数据的代码:
var rawData = context.GetType().GetProperty(TableName).GetValue(context, null);
var truncatedData = ((IQueryable<object>)rawData).ToList();
crudBindingSource.DataSource = new BindingSource { DataSource = truncatedData };
dgvLoadTable.DataSource = crudBindingSource;
dgvLoadTable.Refresh();
现在我想在columnHeader点击时对数据进行排序。我试过这个:
private void dgvLoadTable_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn column = dgvLoadTable.Columns[e.ColumnIndex];
DataGridViewColumn _sortColumn = null;
bool isSortAscending = false;
isSortAscending = (_sortColumn == null || isSortAscending == false);
string direction = isSortAscending ? "ASC" : "DESC";
crudBindingSource.DataSource = context.TableName.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;
//exception here
_sortColumn = column;
}
但是,抛出异常:只能对属于DataGridView控件的单元格执行操作。我该怎么办?
答案 0 :(得分:2)
只需使用datagridview的Sort方法即可获得:
DataGridViewColumn column = dgvLoadTable.Columns[e.ColumnIndex];
ListSortDirection direction = isSortAscending ? ListSortDirection.Ascending : ListSortDirection.Descending;
dgvLoadTable.Sort(column, direction);