New List Items

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

Guest

xHow do I create a new item in a list box that has a different value then the
text? When using the add method the value and the text are the same. I’m
really surprised that listbox1.Items.Add(“valueâ€, “textâ€); doesn’t work. So
how can I do this? Thanks.
 
You can add any type of object you want to a listbox as an item. That means
you can create a class with a all the data you want, simply override the
ToString() method, and add it to a listbox. For example:

private class TestClass
{
public string name = "shane";
public int value = 282;
public override string ToString()
{
return name;
}
}
.....

TestClass t = new TestClass();
listbox1.Items.Add(t); // listbox1 will show an item named "shane"

Chances are that you have already created a class and you just need to
override the ToString method so that it is displayed properly.

ShaneB
 
Tome,

In addition to Shane,

There is a big difference by adding a object to items of the listbox or to
bind a datasource to it.

There are in my opinion two kind of listboxes (better listcontrols), one
which uses the items and the otherone the datasource.

With the datasource you can use the "value" properties of the listbox.

With the items you have to use the objects in the itemarray, which you can
cast back using the DataRowView.

I hope this helps?

Cor
 
Got it; thanks everyone;

ListItem lstNew = new ListItem();
lstNew.Text = "mytest";
lstNew.Value = "myvalue";
lbleft.Items.Add(lstNew);
 
Back
Top