开发者

Linq to objects from Untyped Datatable Unable to cast object of type 'System.Int32' to type 'System.String'

I am completely at a loss for why linq is throwing an Unable to cast object of type 'System.Int32' to type 'System.String' exception. The code is part of a generic function meant to pull the DataTextField and DataValueField out of an untyped DataTable and place them in a list of KeyValuePair(of string, string). I added a for each loop above the linq query to step 开发者_开发百科through each item, and that worked fine. The data returned for the DataValueField is numeric, but its in an untyped set. I tried ToString() on the fields, not sure what to even try next. Any help would be appreciated.

    Private Function GetCurrentBoundControlDT(ByVal StoredProcedure As String, ByVal ParamList As String, ByVal DataTextField As String, ByVal DataValueField As String) As List(Of KeyValuePair(Of String, String))
        Dim ds As DataSet = Nothing
        Dim dt As DataTable = Nothing
        Dim BoundControlDataList As List(Of KeyValuePair(Of String, String)) = Nothing

        If ParamList.Trim <> String.Empty Then
            StoredProcedure = String.Format("{0} {1}", StoredProcedure, ParamList)
        End If

        ds = RG.GetDS(StoredProcedure)

        If Not ds Is Nothing AndAlso ds.Tables.Count > 0 Then
            dt = ds.Tables(0)

            'This works fine
            For Each r As DataRow In dt.Rows
                Dim test1 As String = r(DataTextField)
                Dim test2 As String = r(DataValueField)
                Dim kv As New KeyValuePair(Of String, String)(test1, test2)
            Next
            'Blows up here...
            BoundControlDataList = (From ThisTable In dt.AsEnumerable() _
                    Select New KeyValuePair(Of String, String)(ThisTable.Field(Of String)(DataTextField).ToString(), _
                                               ThisTable.Field(Of String)(DataValueField).ToString())).ToList()
        End If

        Return BoundControlDataList
    End Function


Managed to figure it out. It's not exactly pretty, but works. It seems like (of string) is not so much a cast as a suggestion. I guess (of object) should handle any primitive data correctly and wrapping Convert.ToString() around the field did the trick. The following change is what did it...

            BoundControlDataList = (From t In dt.AsEnumerable() _
                                    Select New KeyValuePair(Of String, String)(Convert.ToString(t.Field(Of Object)(DataTextField).ToString()), _
                                     Convert.ToString(t.Field(Of Object)(DataValueField).ToString()))).ToList()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜