When I first started to use Dictionary<> in C#, I had the idea of using it whenever possible. Then I thought that it should be an easy method to use Dictionary<> to populate combo boxes (with no effort, if possible).
There's no effortless method to use them in such manner, but I figured out my easiest method. The function is easy as follows. You can use it wherever you want, provided with parameters
combo box and
dictionary.
|
public static void FillCombo(System.Windows.Forms.ComboBox cmb,
Dictionary<int,ProjectInfo> projects)
{
// grab a List<> from a Dictionary<>
List<ProjectInfo> lst = new List<ProjectInfo>(projects.Values);
// create an initial item
lst.Insert(0, new ProjectInfo(0, "<PROJECTS>"));
cmb.DataSource = lst;
cmb.ValueMember = "ProjectID";
cmb.DisplayMember = "ProjectName";
}
|
Be careful with these :
- You should define Public Property blocks in your class as I did with
ProjectID and
ProjectName.
- It's convenient to define an appropriate constructor to create initial item
- There's no error handling in the code, you should add your own ones - if appropriate
Here's a Visual Studio 2005 project, in which I demonstrate how to use it.