Fun Infused Games  |   Smooth Operator RSS 

  Home   |    Archive   |    Subscribe   |    Search   |    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


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