以当前显示的顺序获取所选的DataGridViewRows [英] Get selected DataGridViewRows in currently displayed order
问题描述
我有一个 DataGridView
,其中的未绑定数据包含三个不同的 DataColumns
。可以按每一列对行进行排序,但除此之外,不允许对显示的数据进行任何操作。
I have a DataGridView
with unbound data that contains three different DataColumns
. The rows can be sorted by each column, but other than that no manipulation of the displayed data is allowed.
当我查询 SelectedRows
属性时,行以我最初插入它们的顺序排序,而不是像我一样按当前显示或选定的顺序预期。有没有办法改变这种行为?
When I query the SelectedRows
property the rows are sorted in the order I initially inserted them, and not like I expected in the currently displayed or selected order. Is there a way to change this behavior?
推荐答案
我认为没有一种方法可以做到这一点。您需要将排序重做到自己的列表中,然后将IndexOf与SelectedItems配合使用以找出视觉位置。
I don't think there's a one-line way to do this. You will need to redo the sort into your own list, then use IndexOf with the SelectedItems to find out the visual position.
List<DataGridViewRow> l = new List<DataGridViewRow>();
foreach (DataGridViewRow r in dgv.Rows)
{
l.Add(r);
}
l.Sort((x, y) =>
{
IComparable yComparable = (IComparable)x.Cells[dgv.SortedColumn.Index].Value;
IComparable yc = (IComparable)x.Cells[dgv.SortedColumn.Index].Value;
if (dgv.SortOrder == SortOrder.Ascending)
return yc.CompareTo(yComparable);
else
return yComparable.CompareTo(yc);
}
);
foreach(DataGridViewRow r in dgv.SelectedRows)
{
int selectedIndex = l.IndexOf(r);
}
请注意,以上内容尚未经过编译测试,可能需要进行一些调整。
Note the above has not been compile tested and might need some tweaking.
这篇关于以当前显示的顺序获取所选的DataGridViewRows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!