Fun Infused Games  |   Smooth Operator

  Home   |    Archive   |    About
Posts prior to 8/2/2010 may be missing data. If you need one of those posts, please contact kriswd40@yahoo.com and I will try and recover/find it.

No ListItem in Windows Forms
Date 12/18/2009    Tags C#    (0)

After working in .Net web development for years, I'm not spending some time doing Windows Forms development. Today I ran into something rather surprising.

When adding values to a drop down list in ASP.net webpages, I would typically create a ListItem with the Name/Value pare and add that to the dropdown. Very simple to do. Windows Forms does not seem to have an equivalent for adding to comboboxes (there is a ListItem object, but it is not the same thing). There for if you want to add an item to the combobox that has differing name/values, you need to implement your own ListItem-like class.

Thankfully it's pretty easy to do just that (you can just copy the code below if you like)...

public class ComboBoxItem
{
    private string name;
    private int value;

    public ComboBoxItem(string initialName, int initialValue)
    {
        this.name = initialName;
        this.value = initialValue;
    }

    public override string ToString()
    {
        return this.name;
    }
}
Now you can add items to your combobox like so:

this.myComboBox.Items.Add(new ComboBoxItem("Item 1", 1));
this.myComboBox.Items.Add(new ComboBoxItem("Item 2", 2));
this.myComboBox.Items.Add(new ComboBoxItem("Item 3", 3));
Notice that this class also includes an override for ToString(), which allows the display on the combobox to be the Name instead of the Value.

I think you may also be able to use the web (ASP.net) version of this object to do this (System.Web.UI.WebControls.ListItem) but something about mixing Web and Windows Forms elements makes me feel dirty.

I should also note that the code above is mostly borrowed from another website but for the life of me, I cannot find that site again to give them the credit they deserve. If you happen to know which/where that site is, please let me know via email or the comments below.


This article has been view 1963 times.


Comments

No comments for this article.


Add Comments

Name *
Website
  Name the animal in the picture below:

*  
Comment *
Insert Cancel
Things To Click


Tags
Video Games (7)  Trivia or Die (3)  SQL (1)  iOS (3)  Game Dev (11)  Advise (14)  PC (1)  World of Chalk (2)  FIN (20)  Abduction Action! (27)  XBLIG (32)  Abduction Action (1)  Nastier (4)  ASP.net (18)  Absurd (2)  Volchaos (11)  Web (19)  Fin (1)  XNA (40)  Rant (50)  Cool (2)  Visual Studio (1)  Trivia Or Die (1)  Xbox (1)  C# (14)  Sports (11)  Design (2)  Development (13)  Hypership (28)  WP7 (8)  VolChaos (1)  Nasty (34)  Abdction Action! (1)