C# Selecting first row in CategorizedAlphabetical sorted ProperyGrid
I have ProperyGrid loaded with categorised PropertySpec and set to CategorizedAlphabetical sort. When form runs categories then items within categories are sorted. An annoying artefact is that PropertyGrid by default selects the first item after list was sorted and sometimes it scrolls view to selection. If item list is long you end up seeing list scrolled to somewhere in the middle.
Since PropertySpec can be created at runtime I want to always show the top of list on form load. PropertyGrid does not 'easily' expose collections and certainly not in ordered sequen开发者_如何学JAVAce. After googling around I am lead to believe this is not possible?
I came up with below code which proves otherwise.
Snippet will select fist category of sorted list. One could also select first item in that category expanding on the method but for my needs that was unnecessary.
// bind the PropertyTable to PropertyGrid
this.pg_Prefs.SelectedObject = proptable;
// get selected item
GridItem gi = this.pg_Prefs.SelectedGridItem;
// get category for selected item
GridItem pgi = gi.Parent.Parent;
//sort categories
List<GridItem> sortedCats = new List<GridItem>(pgi.GridItems.Cast<GridItem>());
sortedCats.Sort(delegate(GridItem gi1, GridItem gi2) { return gi1.Label.CompareTo(gi2.Label); });
// loop to first category
for (int i = 0; i < pgi.GridItems.Count; i++)
{
if (pgi.GridItems[i] == gi) break; // in case full circle done
// select if first category
if (pgi.GridItems[i].Label == sortedCats[0].Label)
{
pgi.GridItems[i].Select();
break;
}
}
Hope this will help others as well.
The simplified method of actually selecting category once you have sorted list would be to sortedCats[0].Select();
instead of looping through and checking each item. You would have to assert the list is not empty if you wanted to use that shortcut but that would gives some performance improvement...
精彩评论