473,408 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Issues getting an object from a listbox

115 100+
Hi

I have an issue with a list box. I populate the list box using

Expand|Select|Wrap|Line Numbers
  1. listbox1.datasource = myCollectionOfCars
  2. listbox1.databind()
  3.  
When i go to retrieve the selected item from the listbox using

Expand|Select|Wrap|Line Numbers
  1. Car myCar = (Car)listbox1.selecteditem;
  2.  
an error is generated

cannot cast expression type system.web.ui.webcontrols.listitem to type car

i have read several tutorials and many of them use the above code.

Any ideas on how i can return the object from the listbox

Cheers
Truez
Jan 4 '10 #1
11 8790
tlhintoq
3,525 Expert 2GB
Try
(Car)(listbox1.selecteditem);
Where you are trying to cast the selected item of the listbox, not cast the listbox, then get the selected item from that.

or
Car myCar = listbox1.selecteditem as Car
Jan 4 '10 #2
Frinavale
9,735 Expert Mod 8TB
A ListBox contains ListItems.

It doesn't make sense to cast a ListItem into a Car....

You should be using the "id" of the Car to retrieve the appropriate Car from your collection.

-Frinny
Jan 4 '10 #3
truezplaya
115 100+
tlhintoq thanks for the reply however this doesn't solve my issue it is still having problems with casting.

Frinny- I was under the impression that you were able to pass objects in and then get the objects back out of the list, if this is not the case i will have to make a call to my DB to solve this issue

Cheers
Truez
Jan 4 '10 #4
Frinavale
9,735 Expert Mod 8TB
I've never used a ListBox before...Give me a bit to play with one and I'll help you find a solution.

-Frinny
Jan 4 '10 #5
Frinavale
9,735 Expert Mod 8TB
What language are you using?
C# or VB.NET?
Jan 4 '10 #6
truezplaya
115 100+
C#

I have been told that it is possible

and i am also looking in to how i populate the listbox
Jan 4 '10 #7
tlhintoq
3,525 Expert 2GB
A listbox is more than happy to take other types of objects.
For example, I populate a listbox with various DLL plugin objects.

Expand|Select|Wrap|Line Numbers
  1. foreach (string f in Directory.GetFiles(Path))
  2. {
  3.     FileInfo fi = new FileInfo(f);
  4.  
  5.     if (fi.Extension.Equals(".dll"))
  6.     {
  7.         lstPlugins.Items.Add(new Plugin(f));
  8.     }
  9. }
Here we look into a folder and get all the files with extension ".dll".
The path to the file ('f') is passed to a method that will make a Plugin object.
That Plugin is the added to the Items collection of the listbox named 'lstPlugins'
We see in line 7 where an actual Plugin class object is put into the listbox.

If you would like the listbox to display something meaningful for the text I recommend you override the the ToString() method in your 'Car' class. Maybe have it generate something with the year, make and model.
Expand|Select|Wrap|Line Numbers
  1.         public override string ToString()
  2.         {
  3.             return string.Format("{0}, {1}, {2}", this.Year, this.Make, this.Model;
  4.         }
  5.  
This is what any control will receive when it obtains the object as a string, which is what the listbox and most other controls do by default.

This way you aren't casting anything. You are putting a car into the listbox and getting it back out again.
Jan 4 '10 #8
Frinavale
9,735 Expert Mod 8TB
Ok this is what I have:
Expand|Select|Wrap|Line Numbers
  1. private List<Car> cars;
  2.  
  3. protected void Page_Load(object sender, EventArgs e){
  4.   if (!IsPostBack)
  5.   {
  6.     createCarsSource();
  7.     theListBox.DataSource = cars;
  8.     theListBox.DataTextField = "Make";
  9.     theListBox.DataValueField = "Model";
  10.     theListBox.DataBind();
  11.   }
  12. }
  13. private void createCarsSource() {
  14.   cars = new List<Car> { };
  15.   cars.Add(new Car(2010, "Toyota", "Matrix", "Black"));
  16.   cars.Add(new Car(2010, "GM", "Silverado", "Silver"));
  17.   cars.Add(new Car(2010, "Honda", "Civic", "Red"));
  18. }
Where my Car class is as follows:
Expand|Select|Wrap|Line Numbers
  1. class Car
  2. {
  3.   private String _colour;
  4.   private String _make;
  5.   private String _model;
  6.   private int _year;
  7.  
  8.   public String Colour
  9.   {
  10.     get { return _colour; }
  11.     set { _colour = value; }
  12.   }
  13.   public String Make
  14.   {
  15.     get { return _make; }
  16.     set { _make = value; }
  17.   }
  18.   public String Model
  19.   {
  20.     get { return _model; }
  21.     set { _model = value; }
  22.   }
  23.   public int Year
  24.   {
  25.     get { return _year; }
  26.     set { _year = value; }
  27.   }
  28.  
  29.   public Car()  
  30.   {  
  31.   }
  32.   public Car(int year, string make, string model, string colour)
  33.   {
  34.     _year = year;
  35.     _make = make;
  36.     _model = model;
  37.     _colour = colour;
  38.   }
  39. }
The "make" of each car is being displayed as text in the ListBox and the "model" for each car is being used for the value.

ASP.NET is creating a ListItem for each car in my collection of cars. The ListItem's text is what I specified for the DataTextField (the "make" of the car) and the ListItem's value is what I specified for the DataValueField (the "model" of the car).

ListItems are very simple. They only have the following properties:
  • Attributes: Gets a collection of attribute name and value pairs for the ListItem that are not directly supported by the class.
  • Enabled: Gets or sets a value indicating whether the list item is enabled.
  • Selected: Gets or sets a value indicating whether the item is selected.
  • Text: Gets or sets the text displayed in a list control for the item represented by the ListItem.
  • Value: Gets or sets the value associated with the ListItem.

As you can see, you can't exactly store an Object into a ListItem.
It doesn't work that way....

The following code handles the SelectedIndexChanged event for the ListBox.
In it I am retrieving the selected item in the ListBox, re-populating the data source and retrieving the Car Object associated with the selected ListItem:
Expand|Select|Wrap|Line Numbers
  1. protected void theListBox_SelectedIndexChanged(object sender, EventArgs e)
  2. {
  3.   //Retrieving the selected item
  4.   ListItem item = theListBox.SelectedItem;
  5.   String make = item.Text;
  6.   String model = item.Value;
  7.  
  8.   //Recreating the data source so that I can retrieve the Car Object 
  9.   //associated with the selected Item
  10.   createCarsSource();
  11.  
  12.   //Retrieving the selected Car Object from the data source
  13.   Car selectedCar = Array.Find(cars.ToArray(), thecar => (thecar.Make == make && thecar.Model == model));
  14.  
  15.   //msg is a Label on the page...
  16.   //Displaying the car's details
  17.   msg.Text = "<br /> Make: " + selectedCar.Make + "<br/> Model: " + selectedCar.Model + "<br/> Colour: " + selectedCar.Colour + "<br/> Year: " + selectedCar.Year.ToString();
  18.  
  19. }
Please note that I had to recreate the data source. The reason is because ASP.NET is a stateless environment. That means that the collection of cars that I used as the data source for the page the first time the page was loaded is not available the during the postback unless I recreate it. Every object is created, initialized, modified and disposed of for each request...

You can cache your data source though. You can store it in Session or use ASP.NET's cache. There's a lot of ways to cache the data source...




-Frinny
Jan 4 '10 #9
truezplaya
115 100+
Cheers Frinny

I now understand.

Do you know of any web controls that can hold objects without converting them to their own type as such
Jan 4 '10 #10
Frinavale
9,735 Expert Mod 8TB
Not off the top of my head.

You have to remember that you're working with Web technologies here. This means that in order to display things to the end user you have to use HTML..

ASP.NET controls generate HTML for your data...and therefore need to use their own controls to do this. Your .NET Objects are meaningless to the browser/web page when the web page is rendered in the browser...and because of the stateless environment, your .NET server side objects are destroyed each request.

These types of controls may exist, but it's unlikely.

That being said, I can think of ways to do this. It requires using JSON so that the Objects are understood both client and server side.

There are other ways around this too. You can store all of the information required to recreate the object later...

What exactly do you want to do?

-Frinny
Jan 4 '10 #11
truezplaya
115 100+
Well i need to do it using preferably the .net framwork, Since i am working to a dead line i will keep the things you have mentioned in mind and maybe look them up at a later date. I will work from your suggestion of making another call to the database.
Jan 4 '10 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Tim Ottinger | last post by:
I was wondering if there is a good way to get object IDs. In most OO languages, there is a value which is an object ID, which is absolutely specific to the identity of one and exactly one object...
19
by: harry | last post by:
Just want to traverse a listbox's (multi select) items & for those that are selected extract the displayed text - something like below - function getSelectedDescrs(lst) { var buf; var maxItems...
5
by: Steve | last post by:
Given a method lik public byte ReadFile(string filename,int offset, int bufferSize, bool eof can I get an object array of the parameters which will work with any method without explicitly...
3
by: MuZZy | last post by:
Hi, Is it ever possible to obtain an object's current size in managed memory? E.g. if i want to know what's the size in bytes occupied by the particular DataSet object right now (of cource...
6
by: Binoy | last post by:
Hello, I am getting this error once in a while from my web sites. When I will refresh web browser, it goes off and sites are working fine. Directory structures and file names are as below- ...
6
by: Raghu | last post by:
In C#, the typeof keyword can be used to get a type of the class. This does not require object to be created first. However O am not sure how do the same thing in vb. I don't want to create the...
14
by: daveyand | last post by:
Hey guys, I've spent abit of time searching th web and also this group and cant seem to find a solution to my issue. Basically i want to get the current url, and then replace http:// with...
1
by: ced69 | last post by:
having trouble getting marquee to work get object required errors tring t <title>This Month at the Chamberlain Civic Center</title> <link href="styles.css" rel="stylesheet"...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.