You need to write a TypeConvrter and associate it with either the type
or the specific property, implementing GetStandardValues and the
associated methods, presumably checking the context for
instance-specific information.
Something like below.
Marc
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
class Foo
{
private string bar;
[TypeConverter(typeof(BarConverter))]
public string Bar
{
get { return bar; }
set { bar = value; }
}}
class BarConverter : StringConverter // or TypeConverter, etc
{
public override bool
GetStandardValuesSupported(ITypeDescriptorContext context)
{
// is it a drop-down?
return true;
}
public override bool
GetStandardValuesExclusive(ITypeDescriptorContext context)
{
// can the user *only* use the values we provide, or type their
own?
return true;
}
public override StandardValuesCollection
GetStandardValues(ITypeDescriptorContext context)
{
// this list should be the *actual* type we want to store,
// not necessarily strings;
// each will be converted to string when displayed
List<string> list = new List<string>();
list.Add("abc");
list.Add("def");
list.Add("ghi");
if (context != null && context.Instance != null &&
context.PropertyDescriptor != null)
{
// show how to look at the current property/value
// : add the property name and current value (why not)
list.Add(context.PropertyDescriptor.Name);
list.Add((string)context.PropertyDescriptor.GetValue(context.Instance));
}
return new StandardValuesCollection(list);
}
}
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
using (Form form = new Form())
using (PropertyGrid grid = new PropertyGrid())
{
grid.Dock = DockStyle.Fill;
grid.SelectedObject = new Foo();
form.Controls.Add(grid);
Application.Run(form);
}
}
}
Thanks. Here is another way we can do it.
Add this above the property you want displayed in the propertygrid
[TypeConverter(typeof(ListTypeConverter))]
Add this code in your main code
ListTypeConverter.SetList(lst); where lst is a generic list of items.
everytime u add an element to lst call the SetList method.
Add this class to your project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace YourSpace
{
public class ListTypeConverter : TypeConverter
{
private static List m_list = new List();
public override bool GetStandardValuesSupported(ITypeDescriptorContext
context)
{
return true;
}
public override bool GetStandardValuesExclusive(ITypeDescriptorContext
context)
{
return true;
}
private StandardValuesCollection GetValues()
{
return new StandardValuesCollection(m_list);
}
public static void SetList(List list)
{
m_list = list;
}
public override StandardValuesCollection
GetStandardValues(ITypeDescriptorContext context)
{
return GetValues();
}
}
}