C# Selecting first row in CategorizedAlphabetical sorted ProperyGrid

帅比萌擦擦* 提交于 2019-12-08 07:14:32

问题


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 sequence. After googling around I am lead to believe this is not possible?


回答1:


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...



来源:https://stackoverflow.com/questions/6556885/c-sharp-selecting-first-row-in-categorizedalphabetical-sorted-properygrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!