我在ASP.NET中使用SqlDataReader,并且在load_page事件中存在问题

时间:2015-09-20 08:43:32

标签: c# asp.net sqldatareader

protected void Page_Load(object sender, EventArgs e)
{
    con = new SqlConnection(cnString);
    con.Open();

    cmd = new SqlCommand("select * from about_us", con);
    SqlDataReader reader = cmd.ExecuteReader();

    if (!reader.HasRows)
    {
        lblservicedesc.Text = "No Records";
        lblshortdesc.Text = "No Records";
    }
    else
    {
        reader.Read();
        lblshortdesc.Text = reader["AboutShortDescription"].ToString();
        lblservicedesc.Text = reader["ServicesDescription"].ToString();

        reader.Close();
        con.Close();
    }
}

1 个答案:

答案 0 :(得分:0)

将您的代码更改为:

protected void Page_Load(object sender, EventArgs e)
{
    con = new SqlConnection(cnString);
    con.Open();

    cmd = new SqlCommand("select * from about_us", con);
    SqlDataReader reader = cmd.ExecuteReader();

    lblservicedesc.Text = "No Records";
    lblshortdesc.Text = "No Records";

    while (reader.Read())
    {
        lblshortdesc.Text = reader["AboutShortDescription"].ToString();
        lblservicedesc.Text = reader["OnGoingProjectsDescription"].ToString();
    }

    reader.Close();
    con.Close();
}

请注意,如果您有多行,您的标签只会显示最后一行的值。