我完全不知道为什么linq抛出一个Unable来强制转换'System.Int32'类型的对象来输入'System.String'异常。该代码是泛型函数的一部分,用于将DataTextField和DataValueField从无类型DataTable中拉出,并将它们放在KeyValuePair(string,string)列表中。我为linq查询上方的每个循环添加了一个以逐步执行每个项目,并且工作正常。为DataValueField返回的数据是数字,但它在无类型集中。我在字段上尝试了ToString(),不知道接下来要尝试什么。任何帮助将不胜感激。
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
答案 0 :(得分:0)
管理解决问题。它不是很漂亮,但有效。似乎(字符串)不是一个演员而是建议。我猜(对象)应该正确处理任何原始数据,并在字段周围包装Convert.ToString()。以下变化是它做了什么......
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()