我在数据库中的值仍然无法以窗口形式检索它们

时间:2016-05-19 00:39:46

标签: c# sql c#-4.0 ado.net ado.net-entity-data-model

我正在尝试从数据库中的表中检索值,但不能这样做。

这是我的代码

int crs_Id = Convert.ToInt32(Session["crs_id"]);

SqlDataReader r1, r2, r3;

con.Open();

SqlCommand cmd2 = new SqlCommand("Select Course_Title, Description from COURSE where course_ID='" + crs_Id + "'", con);
r1 = cmd2.ExecuteReader();

Label5.Text = r1["Course_Title"].ToString();
Label6.Text = r1["Description"].ToString();

r1.Close();

SqlCommand cmd3 = new SqlCommand("Select Tutor_ID from Teaching where  course_ID='" + crs_Id + "'", con);

r2 = cmd3.ExecuteReader();

if (r2.Read())
{
    int tutor = Convert.ToInt32(r2["Tutor_ID"]);
    r2.Close();

    SqlCommand cmd4 = new SqlCommand("Select Tutor_Name from TUTOR where  Tutor_Id='" + tutor + "'", con);

    r3 = cmd4.ExecuteReader();

    Label7.Text = "Tutor Name is " + r3["Tutor_Name"].ToString() + "";
    r3.Close();
}
else
    r2.Close();

我正在获取例外情况,如屏幕截图所示

enter image description here

1 个答案:

答案 0 :(得分:1)

您收到错误是因为您没有在SqlDataReader返回的ExecuteReader中读取第一行。您可以检查r1.HasRows属性,只有在返回行时才访问列。您还需要执行r1.Read()以获取第一行。

r1 = cmd2.ExecuteReader();
if ( r1.HasRows )
{
    r1.Read();
    Label5.Text = r1["Course_Title"].ToString();
    Label6.Text = r1["Description"].ToString();
}
else
{
    Label5.Text = "";
    Label6.Text = "";
}