Search code examples
c#.netwinformspropertygrid

How do I use Tab to move between properties of winform property grid


I am using Winform's PropertyGrid in my project, it all works fine but the tab order.

I want to switch to next property when I hit Tab but infact, selection moves out of property grid to next control. I am not able to figure out how to get this done ?

Thanks


Solution

  • We should dig into internal parts of PropertyGrid then we can change default Tab behavior of control. At start we should create a derived PropertyGrid and override its ProcessTabKey method.

    In the method, first find the internal PropertyGridView control which is at index 2 in Controls collection. Then using Reflection get its allGridEntries field which is a collection containing all GridItem elements.

    After finding all grid items, find the index of SelectedGridItem in the collection and check if it's not the last item, get the next item by index and select it using Select method of the item.

    using System.Collections;
    using System.Linq;
    using System.Windows.Forms;
    public class ExPropertyGrid : PropertyGrid
    {
        protected override bool ProcessTabKey(bool forward)
        {
            var grid = this.Controls[2];
            var field = grid.GetType().GetField("allGridEntries",
                System.Reflection.BindingFlags.NonPublic |
                System.Reflection.BindingFlags.Instance);
            var entries = (field.GetValue(grid) as IEnumerable).Cast<GridItem>().ToList();
            var index = entries.IndexOf(this.SelectedGridItem);
    
            if (forward && index < entries.Count - 1)
            {
                var next = entries[index + 1];
                next.Select();
                return true;
            }
            return base.ProcessTabKey(forward);
        }
    }