写了 string SQL = "select count(*) from Lesson";
     SqlConnection Conn;
     Conn = new SqlConnection("...");
     SqlCommand Comm = new SqlCommand(SQL,Conn);
     SqlDataReader dr = Comm.ExecuteReader();
如何把表列数显示出来啊?

解决方案 »

  1.   

    没办法DataReader是只读只向前的
    也就是说,他在读这当前这一条记录的时候,是不知道还有没有下一条记录的,等读到没有记录的时候,dr.Read()返回false,这时候你才能知道记录的列数是多少
      

  2.   

    没太明白,你是想读什么,行数吗?如果是读行数:你不就是用的"select count(*) from Lesson"吗?你用SqlDataReader读出来的不就是行数?if (sdr.Read())
    {
        //行数
        int count=Convert.ToInt32(sdr[0]);
    }当然也可以用Scalar:
    int count=Convert.ToInt32(cmd.ExecuteScalar());
      

  3.   

    ok,行了。请问为什么是 sdr[0] ?
      

  4.   

    因为你读的是count(*),只有一条记录啊,且是第一列啊..即首行首列...
      

  5.   

    因为一行,所以只用
    if (sdr.Read())
    {
    }
    而不是用循环读取
    while(sdr.Read())
    {
    }再由于是第一列,所以就直接sdr[0]就OK了...
      

  6.   

    最简单的还是ExecuteScalar:int count=Convert.ToInt32(cmd.ExecuteScalar());
      

  7.   

    哦,明白了。
    还有个问题,如果把字段名在 DropDownList 显示出来,该如何实现啊?
      

  8.   

    DataTable bt = reader.GetSchemaTable();for(int i = 0;i < bt.Columns.Count;i++)
    {
          bt.Columns[i].ColumnName;    //就是字段名了,直接一项一项添加到DropDownList中
                                       //就ok了
    }
      

  9.   

    this.DropDownList1.Items.Add("字段名1");
    this.DropDownList1.Items.Add("字段名2");....这样?
      

  10.   

    我的原意也是想通过一个循环来做:this.DropDownList1.Items.Add("字段名1"); 只是想不懂如何做。
      

  11.   

    我的本意是想通过 dr["lsnName"] 读到的每一行信息都显示到 DropDownList1 中,而这样做的话可能要用到一个循环,那么该如何实现啊?
      

  12.   

    直接绑定就行了...SqlConnection con=SqlConnection("server=.;database=student;uid=sa;pwd=0421");
    SqlDataAdapter sda=new SqlDataAdapter("select * from studentDetails",con);
    DataSet ds=new DataSet();
    sda.Fill(ds,"student");
    this.Dropdownlist1.DataSource=ds.Tables["student"];
    //显示姓名
    this.Dropdownlist1.DisplayMember="sname";
      

  13.   

    在 DropDownList1 中怎么没有 DisplayMember ?
      

  14.   

    不好意思,记混了..这个有吗?DataTextField
      

  15.   

    这个是有了,可是 DropDownList1 中没有显示任何东西
      

  16.   

    asp.net还有关键的一句
    DropDownList1.DataBind();
    不写这句,什么都白搭
      

  17.   

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                BindData();
            }
        }
        public void BindData()
        {
            SqlConnection con = new SqlConnection("server=.;database=student;uid=sa;pwd=0421");
            SqlDataAdapter sda = new SqlDataAdapter("select * from studentInfor", con);
            DataSet ds = new DataSet();
            sda.Fill(ds, "student");
            this.DropDownList1.DataSource = ds.Tables["student"];
            this.DropDownList1.DataTextField = "sname";
            this.DropDownList1.DataBind();
        }
      

  18.   

    我也在怀疑你是不是没加this.DropDownList1.DataBind();我上面的代码是测试成功的...
      

  19.   

    使用Ado.net获取数据库架构信息
    http://blog.csdn.net/zhzuo/archive/2004/07/03/33273.aspx