title: Linq to objects from Untyped Datatable Unable to cast object of type 'System.Int32' to type 'System.String'
body: <p>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.</p>
  
  <pre><code>    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 &lt;&gt; 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 &gt; 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
  </code></pre>