ListItem not available in win forms

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I'm simply trying to add items with values to a combox at runtime in a
windows application. The code below does not work in windows development.

comboBox.Items.Add(new ListItem("text", value));

How can I do this in win forms?
Thanks!
 
The concept you are missing, is that in winforms.. you put Objects into the
combobox.

(I know this, because I didn't get it at first either)

You add objects... like

combobox.Items.Add(new Emp("Smith","John");

You can override the ToString() method..
Or you set which property you want to show up as text.
...

When you pull the selected item, you cast it back to the type of object you
put in there.

Emp ep = myComboBox.SelectedItem as Emp;
if (null!=ep)
{
// do stuff with ep
}
 
really!

No wonder why I've had such poor progress with this. Is there a simple way
to create the object with just a display string and an int value for the
combo box? I'm not sure I understand your code comments below.

Thanks for yolur help.
 
You can put anything in a combobox, be it a string, int, float or a custom
class. The combobox will call the ToString method of the object to find out
what text to display. In your case you'ld want a custom class looking
something like this:

public class ListItem
{
public int Value;
public string Text;
public ListItem(string text, int value)
{
Value = value;
Text = text;
}
public override string ToString()
{
return Text;
}
}

You should probably use properties instead of public fields though, but you
get the idea.

/claes
 
Back
Top