Making windows forms controls strongly typed using generics

By taking advantages of the language features of generics, inheritance, and hiding; adding strong typing to a vanilla user control enables you to retrieve your objects directly without casting them. The unfortunate side-effect of this is that the Visual Studio form designer doesn’t play well with them and will, instead, display an error due to its inability to properly render the control.
 
 
Here are the highlights:
 
public class ComboBox<T> : ComboBox {

    public new IList<T> Items {

        get { return (IList<T>)base.DataSource; }

    }

    public new IList<T> DataSource {

        get { return (IList<T>)base.DataSource; }

        set { base.DataSource = value; }

    }

    public new T SelectedItem {

        get { return (T)base.SelectedItem; }

        set { base.SelectedItem = value; }

    }

    public new T SelectedValue {

        get { return (T)base.SelectedValue; }

        set { base.SelectedValue = value; }

    }

}

 
To decide what you you want the control to display you simply have to set the DisplayMember property of the ComboBox to an attribute of the object type you are binding to the control.
 

public class Person {

    private string firstName, lastName;

    public Person(string firstName, string lastName) {

        this.firstName = firstName;

        this.lastName = lastName;

    }

    public string FirstName {

        get { return firstName; }

        set { firstName = value; }

    }

    public string LastName {

        get { return lastName; }

        set { lastName = value; }

    }

    public string FullName {

        get { return String.Format("{0}, {1}", lastName, firstName); }

    }

}

 

IList<Person> people = new List<Person>();

people.Add(

new Person("Jason", "Hunt"));

people.Add(new Person("Name", "Your"));

personComboBox.DataSource = people;

personComboBox.DisplayMember =

"FullName";

 

 
This results in you being able to acess the object directly when you use the SelectedItem or SelectedValue property of the combobox.
 

Person selectedPerson = personComboBox.SelectedItem;

or 

Person selectedPerson = personComboBox.SelectedValue;

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s