Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 597
Muds Avatar asked Jul 15 '16 16:07

Muds


People also ask

How to use property grid in c#?

To use the property grid, you create a new instance of the PropertyGrid class on a parent control and set SelectedObject to the object to display the properties for. The information displayed in the grid is a snapshot of the properties at the time the object is assigned.

What is property grid?

PropertyGrid is a standard component windows form, which is in the first and second version of the . NET Framework. This component allows us to display properties of practically all types of objects, without writing any additional code.


1 Answers

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);
    }
}
like image 119
Reza Aghaei Avatar answered Oct 17 '22 03:10

Reza Aghaei