无法将类型'int'隐式转换为'System.Data.SqlClient.SqlDataReader'

时间:2009-04-13 23:45:08

标签: casting

我正在尝试使用SqlDataReader来计算我使用的类别数量。

这是我的业务逻辑代码:

// Return count of main categories for homepage
    [DataObjectMethodAttribute(DataObjectMethodType.Select, false)]
    public int GetMainCatCount(int intCategoryID)
    {
        intCategoryID = SQLInject(intCategoryID);

        SqlConnection con = new SqlConnection(conString);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "SELECT COUNT(intCategoryID) "
                        + "FROM  tblCategory "
                        + "WHERE intCategoryID=" + intCategoryID;
        con.Open();
        return (Int32)cmd.ExecuteScalar();
    }

这是我的代码在代码背后页面中进行调用:

public string CountCategory(int intCategoryID)
    {
        SqlDataReader myReader;
        myReader = CategoryBLL.GetMainCatCount(intCategoryID);

        myReader.Close();
        myReader.Dispose();
        return Convert.ToInt32(myReader);
    }

我想使用SqlDataReader的结果来填充标签标签。当我尝试运行此代码时,我收到此错误消息:

无法将类型'int'隐式转换为'System.Data.SqlClient.SqlDataReader'

有谁能请告诉我哪里出错了。 感谢...

3 个答案:

答案 0 :(得分:2)

  

有谁能请告诉我哪里出错了。感谢...

当然:尝试将int转换为SqlDataReader时出错了。您还尝试将SqlDataReader转换为int,稍后再进行。

老实说,你的例子中的类型是如此搞砸,我甚至无法弄清楚代码应该做什么。首先,read this


更多地考虑它,这是一个潜在的固定版本:

public string CountCategory(int intCategoryID)
{
    int count = CategoryBLL.GetMainCatCount(intCategoryID);
    return count.ToString();
}

答案 1 :(得分:1)

您的“GetMainCatCount”方法返回一个int,但您将其返回值赋给SqlDataReader类型的变量:

SqlDataReader myReader;
myReader = CategoryBLL.GetMainCatCount(intCategoryID);

此外,您的CountCategory方法被定义为返回一个字符串,但您从它返回一个Int32(最后一行上的Convert.ToInt32调用的结果)。

答案 2 :(得分:0)

 myReader = CategoryBLL.GetMainCatCount(intCategoryID);

在该行中,您尝试将Int32转换为Type SqlDataReader的对象。

您想尝试myReader.GetMainCatCount(intCatagorID);