Reputation: 281
Hello everyone I've been trying to put some objects in an ASP.NET list box but it's just not working.
I do have an overridden ToString method so I can't understand why this statement won't work. Here's the code that I use:
for (int i = 0; i < fitnessClassList.Count(); i++)
{
lbDisplayItems.Items.Add(fClassList.getFClass(i));
}
And the errors that I get:
Error 2 Argument 1: cannot convert from
'FitClassManage' to
'System.Web.UI.WebControls.ListItem'
Error 1 The best overloaded method match for
'System.Web.UI.WebControls.ListItemCollection.Add(System.Web.UI.WebControls.ListItem)'
has some invalid arguments
Upvotes: 1
Views: 2102
Reputation: 181
Sounds like you want to display a "custom" item in a list box. I got it to work doing the following:
When I programatically added items to myListBox, my custom items were displayed!!
Upvotes: 1
Reputation: 67080
The ASP.NET ListBox is not like the WinForms ListBox. You cannot add any object to him. Its item collection (ListItemCollection) is limited to ListItem (so you can't add your business objects relying on ToString()
for visualization).
Use this code:
ListItem listItem = new ListItem(fitnessClassList.getFitnessClass(i).ToString());
lbDisplayItems.Items.Add(listItem);
Do not forget that if you'll use that ListItem
you won't have the object but its display name (the result of ToString()
). See the link about the ListItem
for more details.
As alternative you may set the DataSource of the ListView to your fitnessClassList
(if it supports that in any way, see this overview on MSDN).
Upvotes: 2
Reputation: 1607
You need to use the .DataSource and .DataBind properties on the listbox.
lbDisplayItems.DataSource = fitnessClassList;
lbDisplayItems.DataBind();
Check out this link for a small example http://asp-net-example.blogspot.com/2011/10/how-to-databind-listbox-using-stack.html
Upvotes: 0
Reputation: 5914
Method Add expects ListItem object (or string, see links below), but you are passing a custom class.
You probably want following:
lbDisplayItems.Items.Add(new ListItem(fitnessClassList.getFitnessClass(i).ToString()));
See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemcollection.aspx - there are only 2 "Add" methods.
See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitem.aspx for available constructors.
Upvotes: 0