User control - Pick value of property from a list of property names of the data source

Viewed 808

I created a UserControl with a property called DataSource. The code is like this:

public partial class MyUserControl : UserControl
{
    public MyUserControl() 
    {
        InitializeComponent();
    }
    private object MyDataSource;

    [Browsable(true)]
    [System.ComponentModel.Bindable(true)]
    [TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
    [Editor("System.Windows.Forms.Design.DataSourceListEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
    public object DataSource
    {
        get
        {
            return MyDataSource;
        }
        set
        {
            if (MyDataSource != value)
                MyDataSource = value;
        }
    }
}

Now I can select the value for DataSource property from a drop down list in design time as image shows:

DataSource property in properties pan

Now what I exactly want is another property called DataColumn that when DataSource has been set to a DataTable , user can select one of that DataTable's columns from a drop down list in properties pan in design time for "DataColumn" property value.Obviously when DataSource has been changed values in DataColumn's drop down list must be changed accordingly

1 Answers

You can decorate your property with following attributes:

[DefaultValue("")]
[TypeConverter("System.Windows.Forms.Design.DataMemberFieldConverter, System.Design")]
[Editor("System.Windows.Forms.Design.DataMemberFieldEditor, System.Design",
    typeof(System.Drawing.Design.UITypeEditor))]
public string DataColumn{ get; set; }

In above code, DataMemberFieldEditor is responsible for showing the drop-down containing property names to pick.

Also DataMemberFieldConverter is responsible to convert None to empty string when you pick None from drop-down.

This is the way that DisplayMember property of ListControl works. You can take a look at its source code.

Related