如何在c#中获取属性网格项的名称,标签和值?

时间:2012-09-07 13:14:34

标签: c# propertygrid

我在propertygrid中定义项目。我的代码在这里:

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

使用此代码,我可以从propertygrid获取Labele和此项的值(对于此示例:书名及其值(例如)学习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

2 个答案:

答案 0 :(得分:2)

使用GridItem.PropertyDescriptor属性:

var propertyName = propertyGrid1.SelectedGridItem.PropertyDescriptor.Name;

答案 1 :(得分:0)

如果继承了PropertyGrid控件,则可以获取所有条目。在继承的类中,放置这个新属性:

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;
            }
        }
    }

希望它有所帮助, 鞍本