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

StackOverflow https://stackoverflow.com/questions/17607041

  •  02-06-2022
  •  | 
  •  

Вопрос

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"
Это было полезно?

Решение

Do as below

Dim DMV As DataRowView = TryCast(LbMCat.SelectedItem, DataRowView)

If DMV IsNot Nothing Then
    SelectedMainCat = DMV.Item("id")
End If

Другие советы

what if you check is the selected value is not integer??

If Not TypeOf (LbMCat.SelectedValue) Is Integer Then
    Dim DMV As DataRowView = LbMCat.SelectedValue 'Here occurs the error
    SelectedMainCat = DMV.Item("id")     
End If

Try to Direct Cast the value :

(DirectCast(LbmCat.SelectedItem, DataRowView)("ID").ToString())

See it here. It may help

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top