Kismet Agbasi
Kismet Agbasi

Reputation: 567

How can I resolve this casting error?

With the help of @competent_tech I have been able to get my comboboxitems to be selected via a button click and parsed through some VB code to get a document displayed.

Everything seemed to be working fine, until I decided to bind the combobox to an XML file using the following code:

<ComboBox Name="ComboBox1" ItemsSource="{Binding Source={StaticResource vehicleID}, XPath=//manualtype/ipck/vin}" IsReadOnly="True"></ComboBox>

This is the code I'm using on the button.click event:

Try
        Dim sFileName As String

        If ComboBox1.SelectedValue IsNot Nothing Then
            sFileName = DirectCast(ComboBox1.SelectedValue, ComboBoxItem).Content.ToString()
            Dim theDocument As New System.Windows.Xps.Packaging.XpsDocument(System.IO.Path.Combine("C:\EMR", sFileName & "ipck.xps"), System.IO.FileAccess.Read)
            DocumentViewer1.Document = theDocument.GetFixedDocumentSequence()
        End If
    Catch ex As Exception
        MessageBox.Show("ERROR: " & ex.Message)
    End Try

The combobox is working fine - displaying the values from the XML file, however, I am now getting an error message whenever I select an item and click the button. The error message states: "UNABLE TO CAST OBJECT OF TYPE 'SYSTEM.STRING' TO TYPE 'SYSTEM.WINDOWS.CONTROLS.COMBOBOXITEM'.

Please help me resolve this problem, as I'd like to be able to update the comboboxitem list via the XML file rather than having to recode the software each time I want to update the list. Thanks.

Upvotes: 0

Views: 167

Answers (1)

brendan
brendan

Reputation: 29976

You're trying to cast ComboBox1.SelectedValue which is a string to a ComboBoxItem object.

I think you could just use:

sFileName = ComboBox1.SelectedValue

Or is your combobox not a list of file names?

Upvotes: 1

Related Questions