Issues getting an object from a listbox

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • truezplaya
    New Member
    • Jul 2007
    • 115

    Issues getting an object from a listbox

    Hi

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

    Code:
    listbox1.datasource = myCollectionOfCars
    listbox1.databind()
    When i go to retrieve the selected item from the listbox using

    Code:
    Car myCar = (Car)listbox1.selecteditem;
    an error is generated

    cannot cast expression type system.web.ui.w ebcontrols.list item 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
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    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.select editem as Car

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      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

      Comment

      • truezplaya
        New Member
        • Jul 2007
        • 115

        #4
        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

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          I've never used a ListBox before...Give me a bit to play with one and I'll help you find a solution.

          -Frinny

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            What language are you using?
            C# or VB.NET?

            Comment

            • truezplaya
              New Member
              • Jul 2007
              • 115

              #7
              C#

              I have been told that it is possible

              and i am also looking in to how i populate the listbox

              Comment

              • tlhintoq
                Recognized Expert Specialist
                • Mar 2008
                • 3532

                #8
                A listbox is more than happy to take other types of objects.
                For example, I populate a listbox with various DLL plugin objects.

                Code:
                foreach (string f in Directory.GetFiles(Path))
                {
                    FileInfo fi = new FileInfo(f);
                
                    if (fi.Extension.Equals(".dll"))
                    {
                        lstPlugins.Items.Add(new Plugin(f));
                    }
                }
                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.
                Code:
                        public override string ToString()
                        {
                            return string.Format("{0}, {1}, {2}", this.Year, this.Make, this.Model;
                        }
                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.

                Comment

                • Frinavale
                  Recognized Expert Expert
                  • Oct 2006
                  • 9749

                  #9
                  Ok this is what I have:
                  Code:
                  private List<Car> cars;
                  
                  protected void Page_Load(object sender, EventArgs e){
                    if (!IsPostBack)
                    {
                      createCarsSource();
                      theListBox.DataSource = cars;
                      theListBox.DataTextField = "Make";
                      theListBox.DataValueField = "Model";
                      theListBox.DataBind();
                    }
                  }
                  private void createCarsSource() {
                    cars = new List<Car> { };
                    cars.Add(new Car(2010, "Toyota", "Matrix", "Black"));
                    cars.Add(new Car(2010, "GM", "Silverado", "Silver"));
                    cars.Add(new Car(2010, "Honda", "Civic", "Red"));
                  }
                  Where my Car class is as follows:
                  Code:
                  class Car
                  {
                    private String _colour;
                    private String _make;
                    private String _model;
                    private int _year;
                  
                    public String Colour
                    {
                      get { return _colour; }
                      set { _colour = value; }
                    }
                    public String Make
                    {
                      get { return _make; }
                      set { _make = value; }
                    }
                    public String Model
                    {
                      get { return _model; }
                      set { _model = value; }
                    }
                    public int Year
                    {
                      get { return _year; }
                      set { _year = value; }
                    }
                  
                    public Car()  
                    {  
                    }
                    public Car(int year, string make, string model, string colour)
                    {
                      _year = year;
                      _make = make;
                      _model = model;
                      _colour = colour;
                    }
                  }
                  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 SelectedIndexCh anged 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:
                  Code:
                  protected void theListBox_SelectedIndexChanged(object sender, EventArgs e)
                  {
                    //Retrieving the selected item
                    ListItem item = theListBox.SelectedItem;
                    String make = item.Text;
                    String model = item.Value;
                              
                    //Recreating the data source so that I can retrieve the Car Object 
                    //associated with the selected Item
                    createCarsSource();
                  
                    //Retrieving the selected Car Object from the data source
                    Car selectedCar = Array.Find(cars.ToArray(), thecar => (thecar.Make == make && thecar.Model == model));
                  
                    //msg is a Label on the page...
                    //Displaying the car's details
                    msg.Text = "<br /> Make: " + selectedCar.Make + "<br/> Model: " + selectedCar.Model + "<br/> Colour: " + selectedCar.Colour + "<br/> Year: " + selectedCar.Year.ToString();
                  
                  }
                  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

                  Comment

                  • truezplaya
                    New Member
                    • Jul 2007
                    • 115

                    #10
                    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

                    Comment

                    • Frinavale
                      Recognized Expert Expert
                      • Oct 2006
                      • 9749

                      #11
                      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

                      Comment

                      • truezplaya
                        New Member
                        • Jul 2007
                        • 115

                        #12
                        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.

                        Comment

                        Working...