Cast error

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cainnech
    New Member
    • Nov 2007
    • 132

    Cast error

    Hello guys,

    I have an issue with a database call. I'm hoping you can help me out.

    I've got a database call that counts the number of entries in the database:
    Code:
            private static Int32 dbCount()
            {
                SqlCommand cmd = new SqlCommand("SELECT COUNT (*) FROM Employees", conn);
                conn.Open();
                Int32 count = (Int32)cmd.ExecuteScalar();
                conn.Close();
                return count;
            }
    Afterwards I'm using this as a check throughout my application:

    Code:
                if (dbCount > 0)
                {
                    // do something
                }
    When I execute this code I'm getting the following error: "Operator '>' cannot be applied to operands of type 'method group' and 'int'"

    So I'm guessing it has something to do with the cast of the dbCount-object but I don't understand why as I already stated that the count-object to be an Int32.

    Who can point out what I've done wrong?

    Thanks
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    You need to read the value returned by your query.

    For example:
    Code:
    private static Int32 dbCount()
    {       
      int count = 0;
      using (SqlConnection conn = new SqlConnection(_CONNECTIONSTRING)) {
        using (new SqlCommand("SELECT COUNT (*) FROM Employees", conn)) {
          conn.Open();
          using (SqlDataReader dr = command.ExecuteReader()) {
            dr.Read();
            count = dr[0];
          }
        }
      }
      return count;
    }
    -Frinny

    Comment

    • Cainnech
      New Member
      • Nov 2007
      • 132

      #3
      Hey Frinny,

      Actually, that wasn't the problem because I only need to return one result so I don't need the DataReader.

      However I've just discovered the problem.
      The call:
      Code:
      if (dbCount > 0)
      should have been
      Code:
      if (dbCount() > 0)
      Those little things can keep you busy for hours...

      Anyway, this topic may be closed.

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Forgot that the ExecuteScalar method returns the first column of the first row in the result.

        Glad you solved your problem.

        -Frinny

        Comment

        Working...