英文:
DataGridView Selecting Row after Sort
问题
I'm using an unbound DataGridView in a Windows form. A few columns are enabled for 'Automatic' sorting (click on column header to sort).
当没有选择任何行时(MyDataGridView.SelectedRows.Count == 0),并且我点击列标题以进行排序时,会选择一行。这行恰好是在填充DGV时添加的第一行。这不是期望的行为;我希望在对列进行排序之前不选择任何行。
或者 - 当我通过单击行来选择一行,然后使用列标题进行排序时,相同的行保持选择状态。这是期望的行为。
此外,如果我通过编程方式取消选择所有行,然后进行排序,之前选择的行现在会被重新选择。这不是期望的行为。
每次执行排序(导致选择发生更改)时,都会触发“SelectionChanged”事件。不幸的是,我无法确定事件的原因。是因为我点击了一行,还是进行了排序?
即使我通过编程方式执行排序,也会出现这个问题。
是否有一种方法可以确保在排序后仅选择之前选择的行?我已经搜索了答案并阅读了许多帖子,但找不到任何有用的信息。
英文:
I'm using an unbound DataGridView in a Windows form. A few columns are enabled for 'Automatic' sorting (click on column header to sort).
When no rows are selected (MyDataGridView.SelectedRows.Count == 0) and I click on the column header to sort, one row is selected. This row happens to be the first row added to the DGV when it was populated. This is undesired behavior; I wish to have no row selected which was not selected before the column was sorted.
Alternately - when I select a row by clicking on it, and then sort using the column header, that same row remains selected. This is desired behavior.
Furthermore, if I then unselect all rows programmatically using MyDataGridView.ClearSelection(), then do the sort, the previously selected row is now reselected. This is undesired behavior.
Each time a sort is performed (which causes the selection to change) the 'SelectionChanged' event fires. Unfortunately I am not able to discern the cause of the event . Was it due to my clicking on a row, or doing a sort?
This problem occurs even if I perform the sort programmatically.
Is there a way to ensure that only previously selected rows are selected after a sort? I have searched for answers and read a number of posts, but can't find anything that helps.
答案1
得分: 0
以下是您要翻译的代码部分:
感谢Jimi,我得到了这个解决方案 - 如果点击标题单元格(用于排序),则通过CellClick事件设置了sortClick标志。它在SelectionChanged事件中被捕获,如果设置了,将清除DGV选择。
private void ArchersGrid_SelectionChanged(object sender, EventArgs e)
{
if (sortClick)
{
sortClick = false;
ArchersGrid.ClearSelection(); // 清除由排序引起的任何选择(没有要选择的行)。
}
else
{
// 用于任何其他选择更改的代码
}
}
private void ArchersGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
{
sortClick = true;
}
else
{
sortClick = false;
}
}
英文:
Thanks to Jimi I wound up with this soution - If click in header cell (for sort) flag sortClick is set by CellClick event. It is picked up in SelectionChanged event and if set will clear the DGV selection.
private void ArchersGrid_SelectionChanged(object sender, EventArgs e)
{
if (sortClick)
{
sortClick = false;
ArchersGrid.ClearSelection(); // Clear any selection caused by sort (no row to select).
}
else
{
// code for any other selection change
}
}
private void ArchersGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
{
sortClick = true;
}
else
{
sortClick = false;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论