程序如下:
目的是在Label1中显示该表的行数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=yh-20120602uzvz\\SQLNEW;Initial Catalog=guestbook;Integrated Security=True");        SqlCommand comm = new SqlCommand("select count(*)from GuestBook", con);
        con.Open();
        int count = (Int32)comm.ExecuteScalar();
        Label1.Text = count.ToString();
        con.Close();
    }
}
调试后报错:“int count = (Int32)comm.ExecuteScalar();附近有语法错误”(调试前无错误显示)

解决方案 »

  1.   

    int count=0;
    object obj = comm.ExecuteScalar(); //返回类型为object if (obj != System.DBNull.Value)
    {
     count=  (Int32)comm.ExecuteScalar();
    }
      

  2.   

      int count = Convert.ToInt32(comm.ExecuteScalar());
      

  3.   

    ExecuteScalar 在用(int)有些字输字符转变不过来比如1.0 或null
      

  4.   

    int count=0;
    object obj = comm.ExecuteScalar(); if (obj != null)
      count = Convert.ToInt32(comm.ExecuteScalar());
      

  5.   

    int count=0;
    object obj = comm.ExecuteScalar(); if (obj != null)
      count = Convert.ToInt32(obj);
      

  6.   

    4楼正解,我依次用上面的方法修改后还是报同样的错,应该是ExecuteScalar的错,而不是格式转换的问题、、
      

  7.   

    ExecuteScalar()返回的是一个object类型,进行类型转换,你不能直接用Int32 int count = int.Parse(comm.ExecuteScalar());
      

  8.   

    楼上是另一种类型转换,修改为:
     object count1 = comm.ExecuteScalar();
                string count0 = count1.ToString();
                int count = int.Parse(count0);
    后类型转换没错了,但、、、错误还是跟原来一样,求大神解救啊!
      

  9.   

    还报错啊,那就检查你的数据库连接字符串,还有你的数据库名称是guestbook,表名是GuestBook,怎么是一样啊?是不是不小心写错啦??跟踪调试一下看看
      

  10.   

    很简单,这不是类型转换不对,仔细看:
    qlCommand comm = new SqlCommand("select count(*)from GuestBook", con);中的sql语句,count(*)这部分的左右括号不匹配,可能一个是中文的括号。