Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selected item of property grid

I need to set the selected item of my property grid. I'm getting an eventargs, which stores a string (this string tells me what property in my propertygrid the user wants to select). The problem is i cannot find a collection of grid items, i can select one from. And also i dont know how to properly create a new GridItem object and set the SelectedGridItem property.

GridItem gridItem = ???;
detailsPropertyGrid.SelectedGridItem = gridItem;

thank you for your help.

Edit:

Its almost working now tahnk you VERY much.

GridItem gi = this.detailsPropertyGrid.EnumerateAllItems().First((item) =>
                item.PropertyDescriptor != null &&
                item.PropertyDescriptor.Name == colName);
        this.detailsPropertyGrid.SelectedGridItem = gi;
        this.detailsPropertyGrid.Select();

The only problem is: Now its selecting the Property Name field. Can I set the focus to the input field of the property?

like image 590
user3596113 Avatar asked Jul 04 '14 10:07

user3596113


1 Answers

Here are a couple of PropertyGrid extensions that can enumerate all items in a grid. This is how you can use it to select one item:

  // get GridItem for a property named "Test"
  GridItem gi = propertyGrid1.EnumerateAllItems().First((item) =>
                    item.PropertyDescriptor != null &&
                    item.PropertyDescriptor.Name == "Test");

  // select it
  propertyGrid1.Focus();
  gi.Select();

  // enter edit mode
  SendKeys.SendWait("{F4}");

  ...

  public static class PropertyGridExtensions
  {
      public static IEnumerable<GridItem> EnumerateAllItems(this PropertyGrid grid)
      {
          if (grid == null)
              yield break;

          // get to root item
          GridItem start = grid.SelectedGridItem;
          while (start.Parent != null)
          {
              start = start.Parent;
          }

          foreach (GridItem item in start.EnumerateAllItems())
          {
              yield return item;
          }
      }

      public static IEnumerable<GridItem> EnumerateAllItems(this GridItem item)
      {
          if (item == null)
              yield break;

          yield return item;
          foreach (GridItem child in item.GridItems)
          {
              foreach (GridItem gc in child.EnumerateAllItems())
              {
                  yield return gc;
              }
          }
      }
  }
like image 157
Simon Mourier Avatar answered Oct 09 '22 13:10

Simon Mourier