2012-09-07 228 views
2

我在propertygrid中定義了item。我的代碼是在這裏:如何在c#中獲取propertygrid項目名稱,標籤和值?

[DisplayName("Title of book"), CategoryAttribute("Books")] 
public string BookName{ get; set; } 

有了這個代碼,我可以得到Labele從PropertyGrid的這個項目的價值(在這個例子中:標題書和它的值(例如)的學習C#) :

private void button1_Click(object sender, EventArgs e) 
{ 
    GridItem gi = propertyGrid1.SelectedGridItem; 
    while (gi.Parent != null) 
    { 
     gi = gi.Parent; 
    } 
    foreach (GridItem item in gi.GridItems) 
    { 
     ParseGridItems(item); //recursive 
    } 
} 

private void ParseGridItems(GridItem gi) 
{ 
    if (gi.GridItemType == GridItemType.Category) 
    { 
     foreach (GridItem item in gi.GridItems) 
     { 
      ParseGridItems(item); 
     } 
    } 
    textBox1.Text += "Lable : "+gi.Label + "\r\n"; 
    if(gi.Value != null) 
     textBox1.Text += "Value : " + gi.Value.ToString() + "\r\n"; 
} 

如何獲取項目名稱?在這個例子中:BOOKNAME

+0

http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx –

+0

我使用propertyGrid1.SelectedObject = myclass;將我的課程設置爲propertygrid項目。我如何訪問視覺propertygrid項目的值和名稱,沒有我的課程? –

回答

2

使用GridItem.PropertyDescriptor屬性:

var propertyName = propertyGrid1.SelectedGridItem.PropertyDescriptor.Name; 
+0

謝謝,gi.PropertyDescriptor.Name +「:」+ gi.Value.ToString(); –

0

你可以得到所有的項目,如果你繼承PropertyGrid控件。在inherrited類,把這個新屬性:

public GridItem[] Items 
    { 
     get 
     { 
      try 
      { 
       System.Reflection.FieldInfo field_gridView = typeof(PropertyGrid).GetField("gridView", System.Reflection.BindingFlags.NonPublic 
        | System.Reflection.BindingFlags.Instance); 

       object gridView = field_gridView.GetValue(this); 

       System.Reflection.MethodInfo gridView_method_GetAllGridEntries = gridView.GetType().GetMethod("GetAllGridEntries", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance, null, new Type[0], null); 

       object gridEntries_collection = gridView_method_GetAllGridEntries.Invoke(gridView, new object[0]); 

       System.Reflection.MethodInfo gridEntries_collection_count_method = gridEntries_collection.GetType().GetMethod("get_Count"); 

       int count_entries = (int) gridEntries_collection_count_method.Invoke(gridEntries_collection, new object[0]); 

       System.Reflection.MethodInfo gridEntries_collection_getItem_method = gridEntries_collection.GetType().GetMethod("get_Item", new Type[] { typeof(int) }); 

       GridItem[] entries = new GridItem[count_entries]; 

       for (int i = 0; i < count_entries; i++) 
       { 
        entries[i] = gridEntries_collection_getItem_method.Invoke(gridEntries_collection, new object[] { i }) as GridItem; 
       } 

       return entries; 
      } 
      catch 
      { 
       throw; 
      } 
     } 
    } 

希望它能幫助, 鞍本。