none
How to load a ListBox from an ArrayList?

    Question

  • Hi, I tried the sample from MSDN
    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemwindowsformslistcontrolclassdisplaymembertopic.asp

    But it did not compile.
     The ListBox is loaded thus:


    Dim USStates As New ArrayList
    USStates.Add(
    New USState("Washington", "WA"))
    USStates.Add(
    New USState("West Virginia", "WV"))
    USStates.Add(
    New USState("Wisconsin", "WI"))
    USStates.Add(
    New USState("Wyoming", "WY"))
    ListBox1.DataSource = USStates
    ListBox1.DisplayMember = "LongName"
    ListBox1.ValueMember = "ShortName"


     



    But then I run into trouble here:



    Private Sub ListBox1_SelectedValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedValueChanged

       If ListBox1.SelectedIndex <> -1 Then
            
    textBox1.Text = ListBox1.SelectedValue ' Raises InvalidCastException
       
    End If
    End Sub

     


    I get the following message:

    An unhandled exception of type 'System.InvalidCastException' occurred in microsoft.visualbasic.dll

    Additional information: Det går inte att omvandla typen USState till typen String.
    Translating to "Cannot convert the type USState to the type String".

    What is wrong here?

    Wednesday, December 07, 2005 3:22 PM

Answers

  • ListBox1.SelectedValue will be an object, while textBox1.Text is expecting text.

    I think that sample code is simply missing a .ToString at the end:

    textBox1.Text = ListBox1.SelectedValue.ToString




    Wednesday, December 07, 2005 4:41 PM

All replies

  • ListBox1.SelectedValue will be an object, while textBox1.Text is expecting text.

    I think that sample code is simply missing a .ToString at the end:

    textBox1.Text = ListBox1.SelectedValue.ToString




    Wednesday, December 07, 2005 4:41 PM
  • Thanks Jason, you were quit right.

    But I'm still a bit confused, .SelectedValue should not have returned an USState type object, it should have returned an object of the type used in the USState.ShortName property, which is String.
    And even if it did return an USState object, the .ToString function should not have returned the correct answer but a concatenation of both the long and short name.

    So why does VS tell me I got an USState when I clearly got a String casted as an object?
    Wednesday, December 07, 2005 10:39 PM
  • I get this, but how do you load a ListBox from a collection.  Specifically, I wanted to populate a ListBox with the contents of a DataTableCollection....eg DataSource.Tables property..

     

    I can see a List property but that is protected. What is the use of such a property which appears to be spot on the mark, or is it that it isn't implemented and is only intended to be overriden?

     

    Regards

    Craig Dunstan

    Wednesday, January 18, 2006 3:25 AM