gpt4 book ai didi

c# - 错误无法将类型为“System.Int32”的对象转换为类型为“System.String”的对象

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:09 25 4
gpt4 key购买 nike

我正在使用下面的函数从数据库获取值。

问题是当我选择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;
}
}
}
}


用户表结构

UserID   type int
UserName type nvarchar(50)
Password type nvarchar(50)

最佳答案

尝试result.Add(dr.GetValue(0).ToString());

为了避免GetValue()的返回为null,请执行以下操作-

result.Add((sqlreader.IsDBNull(0) ? "" : dr.GetValue(0).ToString());

关于c# - 错误无法将类型为“System.Int32”的对象转换为类型为“System.String”的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com