asp.net c#在标签中显示数据 - System.Web.UI.WebControls.Label

时间:2018-05-30 15:02:28

标签: c# asp.net

我试图使用C#将SQL中的值拉入ASP.Net中的标签,但它只是在调度System.Web.UI.WebControls.Label。 我已经在调试中运行,我可以看到C#正在拉回我期望的值,我该如何在ASP中显示它?

C#代码:

string connectionString = ConfigurationManager.ConnectionStrings["SEV2"].ConnectionString;
string commandText = "SELECT COUNT (*) AS TotalApplicants FROM (SELECT tbl_Candidate.CandID, tbl_Candidate.FirstName, tbl_Candidate.LastName FROM tbl_Candidate INNER JOIN tbl_CandProfile ON tbl_Candidate.CandID = tbl_CandProfile.CandID) a";

DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand command = new SqlCommand(commandText, con);
SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    lblTotalApplicants = reader["TotalApplicants"].ToString();
}
this.DataBind();
con.Close();

ASP.Net代码:

<div class="stat-content dib">
    <div class="stat-text">Total Applicants</div>
    <asp:Label ID="lblTotalApplicants" class="stat-digit" runat="server" Text="">
        <%# lblTotalApplicants %>
    </asp:Label>
</div>

2 个答案:

答案 0 :(得分:0)

您不应该绑定Label控件中的内容。您应该使用Text属性。这应该做的工作:

<asp:Label ID="lblTotalApplicants" Text="<%# totalApplicants %>" class="stat-digit" runat="server">

请注意,totalApplicants应该是您网页上的protected变量。

您也可以设置Text属性服务器端:

while (reader.Read())
{
    lblTotalApplicants.Text = reader["TotalApplicants"].ToString();
}

答案 1 :(得分:0)

您的查询返回一个整数值,因此您要使用ExecuteScalar

代码背后

protected void Page_Load(object sender, EventArgs e)
{    
    string connectionString = 
         ConfigurationManager.ConnectionStrings["SEV2"].ConnectionString;
    string commandText = "YOUR QUERY";

    using (var con = new SqlConnection(connectionString))
    using (var command = new SqlCommand(commandText, con))
    {
        con.Open();
        lblTotalApplicants.Text = command.ExecuteScalar().ToString();
    }
}

ASPX

删除<%# lblTotalApplicants %>

<div class="stat-content dib">
    <div class="stat-text">Total Applicants</div>
    <asp:Label ID="lblTotalApplicants" class="stat-digit" runat="server" />
</div>