Search code examples
c#propertygrid

How do I create a Modal UITypeEditor for a string property?


I have a property which is stored as a string and is to be edited via a PropertyGrid It is kept as a set of comma separated values e.g ABC, DEF, GHI. My users could edit the string directly but the values come from a closed set of values. So it is easier and safer for them to pick from a list.

I have written a simple custom UITypeEditor based on the excellent answer here

I also reviewed this but I did not really understand it might relate to my problem. 8-(

I set up a simple form that allows the user to pick from a list and the picked values are added to value to be returned. My problem is that the value is not being returned. I wondered if this is something to do with the immutability of strings. However it is probably something simple and stupid that I am doing.

Here is my code for the type editor based on Marc's answer:

   public class AirlineCodesEditor : UITypeEditor
    {

        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value)
        {
            var svc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            var codes = value as string;

            if (svc != null && codes != null)
            {
                using (var form = new AirlineCodesEditorGUI())
                {
                    form.Value = codes;
                    if (svc.ShowDialog(form) == DialogResult.OK)
                    {
                        codes = form.Value; // update object
                    }
                }
            }

            return value; // can also replace the wrapper object here
        }

    }

The form is trivial for my test I just edited the textbox with some new values:

   public partial class AirlineCodesEditorGUI : Form
    {


        public AirlineCodesEditorGUI()
        {
            InitializeComponent();

        }


        public string Value {
            get
            {
                return airlineCodes.Text;
            }

            set
            {
                airlineCodes.Text = value;
            } 
        }

        private void OnCloseButtonClick(object sender, System.EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }
    }  

Perhaps someone would put me out of my misery.


Solution

  • You just need to return the value from the form, like this:

     if (svc.ShowDialog(form) == DialogResult.OK)
     {
         value = form.Value;
     }