Groups | Blog | Home
all groups > dotnet general > november 2004 >

dotnet general : New List Items


Tome73
11/6/2004 8:21:02 PM
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
ShaneB
11/6/2004 11:56:54 PM
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


[quoted text, click to view]

Cor Ligthert
11/7/2004 10:23:20 AM
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

"Tome73" <Tome73@discussions.microsoft.com>

[quoted text, click to view]

Tome73
11/7/2004 7:23:01 PM
Got it; thanks everyone;

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


[quoted text, click to view]
AddThis Social Bookmark Button