private void button1_Click(object sender, EventArgs e) { string name; name = textBox5.Text; SqlConnection con10 = new SqlConnection("con strn"); SqlCommand cmd10 = new SqlCommand("select * from sumant where username=@name"); cmd10.Parameters.AddWithValue("@name",name); cmd10.Connection = con10; cmd10.Connection.Open();//line 7 SqlDataReader dr = cmd10.ExecuteReader(); } if ( textBox2.Text == dr[2].ToString()) { //do something; }
当我调试到第7行时,还可以,但是在那之后dr抛出异常: Invalid attempt to read when no data is present. 这是不可能的,因为我的表中确实有用户名= sumant的数据。请告诉我’if’陈述是否正确.........
Invalid attempt to read when no data is present.
以及如何清除错误?
您必须致电DataReader.Read以获取结果:
DataReader.Read
SqlDataReader dr = cmd10.ExecuteReader(); if (dr.Read()) { // read data for first record here }
DataReader.Read()返回一个bool指示,指示是否还有更多的数据块要读取,因此,如果有多个结果,则可以执行以下操作:
DataReader.Read()
bool
while (dr.Read()) { // read data for each record here }