【问题标题】:Error Unable to cast object of type 'System.Int32' to type 'System.String'错误无法将“System.Int32”类型的对象转换为“System.String”类型
【发布时间】:2016-06-25 20:35:35
【问题描述】:

我正在使用以下函数从数据库中获取值。

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

【问题讨论】:

  • 你能告诉我们你的表结构吗?

标签: c# asp.net


【解决方案1】:

当我选择 int 类型的列时

根据代码,您正在尝试选择string 类型的列:

dr.GetString(0)

如果列是int,则获取int:

dr.GetInt32(0)

然后您可以将其转换为 string 用于您的列表:

result.Add(dr.GetInt32(0).ToString());

具体关于错误,注意the documentation中的文字:

不执行任何转换;因此,检索到的数据必须已经是一个字符串。

【讨论】:

  • 这应该被标记为答案,因为它很好地解释了问题,也解释了解决它
【解决方案2】:

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

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

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

【讨论】:

  • 你能解释一下为什么答案是这样的吗?如果您不解释问题以及如何解决以及为什么会出现问题,那么对于任何人实际理解问题都没有多大帮助。
  • 太棒了。如果它解决了您的问题,请选择作为答案。谢谢
  • 另外,以防万一它可能是空值,我将添加约束以检查空条件。我会把它添加到我的答案中。
【解决方案3】:

我遇到了同样类型的错误:'System.Int32' to type 'System.String'

这里如果要绑定字符串值的意思是

dr.GetString(1)

如果要打印int值意味着

dr.GetInt32(0)

我又遇到了一个错误:指定的演员表无效。

如果你想要字符串意味着你需要放

dr.GetString(1)

最初我做了dr.GetString(0),这表明指定的演员表无效。 如果您需要 int 值,则同样的事情意味着您需要输入 dr.GetInt32(0) 而不是 dr.GetInt32(1)

【讨论】:

    猜你喜欢
    • 2014-02-03
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2021-10-25
    • 1970-01-01
    相关资源
    最近更新 更多