Search code examples
vb.netdatarowview

Unable to cast object of type 'System.Int32' to type 'System.Data.DataRowView'


I need to retrieve the "id" from datasource of the selected item, but it always throws the same error mentionned in the title. Here is my code

        Dim DMV As DataRowView = LbMCat.SelectedValue 'Here occurs the error
    SelectedMainCat = DMV.Item("id") 

    'Filling the SUB Categories part / same code used to fill Main categories
    Dim DataAdapterCats As New MySqlDataAdapter("SELECT * From catS where maincat = '" & SelectedMainCat & "';", MySqlConnection)
    Dim dsSc As New DataSet
    DataAdapterCats.Fill(dsSc, "SubCategories")
    Dim SDataTable As DataTable = dsSc.Tables(0)
    LbSCat.DataSource = SDataTable
    LbSCat.DisplayMember = "title"
    LbSCat.ValueMember = "id"

Solution

  • Do as below

    Dim DMV As DataRowView = TryCast(LbMCat.SelectedItem, DataRowView)
    
    If DMV IsNot Nothing Then
        SelectedMainCat = DMV.Item("id")
    End If