SqlConnection con = DB.creatCon();
            con.Open();
            SqlCommand cmd = new SqlCommand("select cusTel,cusEmail from personCus where cusID=" + this.dropPerName.SelectedValue.ToString(), con);
            SqlDataReader sdr = cmd.ExecuteReader();
            if (sdr.Read())
            {
                this.txtPerTel.Text = sdr[0].ToString();
                this.txtPerEmail.Text = sdr[1].ToString();
               
           }
            sdr.Close();
            con.Close();
上面这段代码,如果把if(sdr.Read())去掉后,明明有数据,它也会报错说不能读空数据,请问这是为什么?
  

解决方案 »

  1.   

    加一条打印语句  打印出查询字符串 然后拷贝到查询分析器 看是不是真的没有记录
    System.Diagnostics.Debug.Print("select cusTel,cusEmail from personCus where cusID=" + this.dropPerName.SelectedValue.ToString() );-----------------------
    SqlConnection con = DB.creatCon();
                con.Open();
                SqlCommand cmd = new SqlCommand("select cusTel,cusEmail from personCus where cusID=" + this.dropPerName.SelectedValue.ToString(), con);
                 System.Diagnostics.Debug.Print("select cusTel,cusEmail from personCus where cusID=" + this.dropPerName.SelectedValue.ToString() );
                SqlDataReader sdr = cmd.ExecuteReader();
                if (sdr.Read())
                {
                    this.txtPerTel.Text = sdr[0].ToString();
                    this.txtPerEmail.Text = sdr[1].ToString();
                   
               }
                sdr.Close();
                con.Close();
      

  2.   

    因为用SqlDataReader read()读取数据之前,先要运行sdr.Read()后读取数据,具体见微软编的ADO.NET编程指南,第四章。