我有一个DataGridView绑定到绑定到BindingList的BindingSource。我可以按预期通过单击列标题对DataGridView进行排序。但是当我将一个项目放到DataGridView上时,它会出现在列表的底部而不是正确的排序位置。我在StackOverflow网格中找到了代码来检查网格的SortOrder和SortedColumn属性,如果设置了它们,那么就采用网格。但是,当我在DragDrop处理程序中放置断点时,我发现SortOrder设置为None而SortedColumn为null。
这是DragDrop处理程序:
private void dgvCoils_DragDrop(object sender, DragEventArgs e)
{
int? coilStack = m_draggedCoil.Stack;
m_currentCharge.RemoveCoil(m_draggedCoil);
if (coilStack.HasValue)
{
DisplayStack(coilStack.Value);
}
if (!m_inventoryList.Any(coil => coil.Coil_id == m_draggedCoil.Coil_id))
{
m_inventoryList.Add(m_draggedCoil);
if (dgvCoils.SortOrder != SortOrder.None && dgvCoils.SortedColumn != null)
{
ListSortDirection dir = ListSortDirection.Ascending;
if (dgvCoils.SortOrder == SortOrder.Descending) dir = ListSortDirection.Descending;
dgvCoils.Sort(dgvCoils.SortedColumn, dir);
}
}
}
这是我创建列表并将源绑定到它的代码:
InventorySet coilSet = new InventorySet(m_db);
coilSet.FilterOnField(coilSet.m_archived, 0);
coilSet.Open();
// coilBindingSource.DataSource = coilSet.UnderlyingTable;
while (!coilSet.IsEOF())
{
m_inventoryList.Add(coilSet.ExportData());
coilSet.MoveNext();
}
coilBindingSource.DataSource = m_inventoryList;
coilBindingSource.ResetBindings(false);
dgvCoils.Refresh();
我没有在BindingSource对象中设置任何Sort列。我需要吗?
如果是BindingList中的基础列表,我是否需要使用BindingSource?
编辑: 回顾一下我的源代码,我记得我必须在我的ColumnHeaderMouseClick事件处理程序中添加代码才能使排序正常工作。这是处理程序:
private void dgvCoils_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string strColumnName = dgvCoils.Columns[e.ColumnIndex].DataPropertyName;
SortOrder strSortOrder = GetSortOrder(dgvCoils, e.ColumnIndex);
if (strSortOrder == SortOrder.Ascending)
{
m_inventoryList = new BindingList<InventorySetData>(m_inventoryList.OrderBy(x => typeof(InventorySetData).GetProperty(strColumnName).GetValue(x, null)).ToList());
}
else
{
m_inventoryList = new BindingList<InventorySetData>(m_inventoryList.OrderByDescending(x => typeof(InventorySetData).GetProperty(strColumnName).GetValue(x, null)).ToList());
}
dgvCoils.DataSource = m_inventoryList;
dgvCoils.Columns[e.ColumnIndex].HeaderCell.SortGlyphDirection = strSortOrder;
}
我猜我在编程方面做得太多了,而不是让DataGridView按照它的设计去做。