Custom FileNameEditor

2.6k views Asked by At

I want to implement a custom FileNameEditor; I want to set my own filter and I want to be able to select multiple files.

public class Settings
{
    [EditorAttribute(typeof(FileNamesEditor), typeof(System.Drawing.Design.UITypeEditor))]
    public string FileNames { get; set; }
}

public class FileNamesEditor : FileNameEditor
{
    protected override void InitializeDialog(OpenFileDialog openFileDialog)
    {
        openFileDialog.Multiselect = true;
        openFileDialog.Filter = "Word|*.docx|All|*.*";
        base.InitializeDialog(openFileDialog);

    }
}

This ignores the filter property and although I am able to select multiple files I can't assign them to my Settings.FileNames property because Settings.FileNames is of type string[] and the result of the derived class is string. How can I tell my derived class to return the openFileDialog's FileNames and how to make the filter work? What am I missing?

3

There are 3 answers

1
Llarian On

Okay, this is how it works...

public class FileNamesEditor : UITypeEditor
{
    private OpenFileDialog ofd;
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        if ((context != null) && (provider != null))
        {
            IWindowsFormsEditorService editorService =
            (IWindowsFormsEditorService)
            provider.GetService(typeof(IWindowsFormsEditorService));
            if (editorService != null)
            {
                ofd = new OpenFileDialog();
                ofd.Multiselect = true;
                ofd.Filter = "Word|*.docx|All|*.*";
                ofd.FileName = "";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    return ofd.FileNames;
                }
            }
        }
        return base.EditValue(context, provider, value);
    }
}
2
rfcdejong On

Perhaps use an ArrayEditor for the string[]

public class Settings
{
  [EditorAttribute(typeof(System.ComponentModel.Design.ArrayEditor),  typeof(System.Drawing.Design.UITypeEditor))]
  public string[] FileNames { get ; set; }
}
0
Ron Sigal On

The original code worked for me, except for a needed re-ordering. You need to call the base.Initialize before your changes, or they get overwritten (debugging will show it nicely)

public class FileNamesEditor : FileNameEditor
{
    protected override void InitializeDialog(OpenFileDialog openFileDialog)
    {
        base.InitializeDialog(openFileDialog);
        openFileDialog.Multiselect = true;
        openFileDialog.Filter = "Word|*.docx|All|*.*";
    }
}