错误无法将类型为"System.Int32"的对象转换为类型为"System.String"的对象 [英] Error Unable to cast object of type 'System.Int32' to type 'System.String'
本文介绍了错误无法将类型为"System.Int32"的对象转换为类型为"System.String"的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下函数从数据库获取值.
I am using below function to get values from database.
问题是当我选择int类型的列时.
The problem is when i select column of type int.
我收到此错误无法将类型为'System.Int32'的对象转换为类型为'System.String'.
在此行 result.Add(dr.GetString(0));
代码
[WebMethod]
public static List<string> GetAutoCompleteData(string value, string filterBy)
{
string strConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
con.Open();
string command = string.Format("select {0} from Users where {0} LIKE '%'+@SearchText+'%'", filterBy);
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("@SearchText", value);
using (SqlDataReader dr = cmd.ExecuteReader())
{
List<string> result = new List<string>();
while (dr.Read())
{
result.Add(dr.GetString(0));
}
return result;
}
}
}
}
用户表结构
UserID type int
UserName type nvarchar(50)
Password type nvarchar(50)
推荐答案
尝试 result.Add(dr.GetValue(0).ToString());
为避免GetValue()的返回为空,请执行以下操作-
To avoid the return of GetValue() being null, do this -
result.Add((sqlreader.IsDBNull(0) ? "" : dr.GetValue(0).ToString());
这篇关于错误无法将类型为"System.Int32"的对象转换为类型为"System.String"的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文