Search code examples
c#propertygrid

Select a property in the property grid


I am using a PropertyGrid to display the content of an object to the user.

This PropertyGrid is synchronized with an Excel sheet, assuming a cell value match a property value.

As the user selects a property in the PropertyGrid, the application highlights the corresponding cell in the Excel sheet which is opened beside. I can do this using the SelectedGridItemChanged event.

Now, I want to have a property selected in my PropertyGrid when the user selects a cell in the Excel sheet.

void myWorkbook_SheetSelectionChangeEvent(NetOffice.COMObject Sh, Excel.Range Target)
{
    if (eventMask > 0)
        return;

    try
    {
        eventMask++;

        this.Invoke(new Action(() => 
        {
            propertyGrid1.SelectedGridItem = ... // ?
        }
    }
    finally
    {
        eventMask--;
    }
}

I noticed that the SelectedGridItem can be written to.

Unfortunately I do not find a way to access the GridItems collection of my PropertyGrid so I can look for the right GridItem and select it.

How can I do this?


Solution

  • You can get all the GridItems from the root. I am using the below code to retrieve all the griditems within a property grid

    private GridItem Root
        {
            get
            {
                GridItem aRoot = myPropertyGrid.SelectedGridItem;
                do
                {
                    aRoot = aRoot.Parent ?? aRoot;
                } while (aRoot.Parent != null);
                return aRoot;
            }
        }
    

    and pass the root to the below method

    private IList<GridItem> GetAllChildGridItems(GridItem theParent)
        {
            List<GridItem> aGridItems = new List<GridItem>();
            foreach (GridItem aItem in theParent.GridItems)
            {
                aGridItems.Add(aItem);
                if (aItem.GridItems.Count > 0)
                {
                    aGridItems.AddRange(GetAllChildGridItems(aItem));
                }
            }
            return aGridItems;
        }