将值从数据库加载到标签的正确方法是什么?

时间:2013-03-12 17:49:28

标签: c# asp.net

Admin.aspx

       <div id="valueIntroduction" class="labelarea" runat="server">   </div>
       <div  class="line"></div>

Admin.aspx.cs

        SqlConnection NewConn = new SqlConnection(ConfigurationManager.ConnectionStrings["SoicConnection"].ConnectionString);
        NewConn.Open();
        SqlCommand NewComm = new SqlCommand();
        SqlCommand NewComm1 = new SqlCommand();

        if (Department.Items[0].Selected)
        {
                firstPanel.Visible = true;
                myLegend.InnerText = "Informatics";
                NewComm.CommandText = "getTextHeaderINFO";

                NewComm.CommandType = CommandType.StoredProcedure;
                NewComm.Connection = NewConn;
                NewComm.CommandTimeout = 3000;
                SqlDataReader results = NewComm.ExecuteReader();

                while (results.Read())
                {
                     Response.Write(results["TEXT_CONTENT"].ToString());
                     Label valueIntroduction = results["TEXT_CONTENT"];
                }

         }

我正在尝试的是从数据库中获取值并将其加载到标签中。我是.net和stackoverflow的新手。很抱歉,如果我不知道如何正确使用这个论坛。

1 个答案:

答案 0 :(得分:1)

使用SqlDataReader results = NewComm.ExecuteSclar();

而不是SqlDataReader results = NewComm.ExecuteReader();

并将标签文本设置为结果。

   ResultLabel.Text = NewComm.ExecuteScalar().ToString();
   conn.Close();

这是一个smililar queston
Display SQL query result in a label in asp.net

修改

第一张唱片

 int counter=0;
 while (results.Read())
 {
     if(counter++=0)
     {
          ResultLabel.Text = results["TEXT_CONTENT"].ToString();
          conn.Close();
          break;
     }

 }
相关问题