我得按钮onclick事件如下:
{
     string Sqlstring = "server=(local);uid=sa;pwd=123456;database=MyData";
     SqlConnection SqlCon = new SqlConnection(Sqlstring);
     SqlCon.Open();     string sqlstr = "select UserID,Balance from MYUser ";
     SqlCommand SqlCom = new SqlCommand(sqlstr,SqlCon);/*4*/SqlDataReader rdResult = SqlCom.ExecuteReader();
/*3*/this.textBox1.Text = rdResult[0].ToString();
/*2*/rdResult.Close();
/*1*/SqlCon.Close();
}上面/*3*/位置处总说“在没有任何数据时进行无效的读取尝试”,应该是说没有数据的时候我用了ToString方法,也就是说没有读出来数据。而我把1~4行变为,只读取第一行第一列,可以顺利执行显示出我的数据,这证明我上面的数据库联接应该没有问题,不知道用ExecuteReader  有什么注意事项吗?
{
   string strTemp = SqlCom.ExecuteScalar();
   this.textBox1.Text = strTemp;
   SqlCon.Close();
}

解决方案 »

  1.   

    while(rdResult.Read())
    {
       this.textBox1.Text=rdResult[0].ToString()
    }
      

  2.   

    为什么要这个样子,执行  SqlDataReader rdResult = SqlCom.ExecuteReader(); 后  rdResult是什么状态,这个是什么原理?
      

  3.   

    {
         string Sqlstring = "server=(local);uid=sa;pwd=123456;database=MyData";
         SqlConnection SqlCon = new SqlConnection(Sqlstring);
         SqlCon.Open();     string sqlstr = "select UserID,Balance from MYUser ";
         SqlCommand SqlCom = new SqlCommand(sqlstr,SqlCon);    SqlDataReader rdResult;
        rdResult= SqlCom .ExecuteReader();
        // Always call Read before accessing data.
        while (rdResult.Read()) {
           this.textBox1.Text = rdResult.GetString(0);
        }
        // always call Close when done reading.
        rdResult.Close();
        // Close the connection when done with it.
        SqlCon.Close();
    }