我使用下面的函数从数据库中获取值.
问题是当我选择int类型的列时.
我收到这个错误 Unable to cast object of type 'System.Int32' to type '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;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
用户表结构
UserID type int
UserName type nvarchar(50)
Password type nvarchar(50)
Run Code Online (Sandbox Code Playgroud)
当我选择int类型的列
根据代码,您尝试选择类型的列string:
dr.GetString(0)
Run Code Online (Sandbox Code Playgroud)
如果列是a int,那么得到一个int:
dr.GetInt32(0)
Run Code Online (Sandbox Code Playgroud)
您可以将其转换为a string列表:
result.Add(dr.GetInt32(0).ToString());
Run Code Online (Sandbox Code Playgroud)
没有进行转换; 因此,检索到的数据必须已经是一个字符串.
| 归档时间: |
|
| 查看次数: |
8325 次 |
| 最近记录: |