Bilgin's Blog
Crumpler Wee Bee

 


My Crumpler Wee Bee


For my quest of the ideal notebook bag and my review of Crumpler Wee Bee, click

Wee Bee review

Programmers' Blog
Programmer's Blog

Specific hints and tricks for C# programmers.

click for "Programmers' Blog"

From Dictionary to ComboBox
Minimize

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(0new 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.

Bilgin Esme, Feb 2007
About  |  Affiliate Program  |  Sitemap  |  FAQ's Privacy Statement  |  Terms Of Use
Copyright 2009 by Bilgin Esme