I'm trying to pull a value from SQL into a label in ASP.Net using C# but it is just dispaying System.Web.UI.WebControls.Label.
I've run in debug and I can see the C# is pulling back the value I expect, how do I get this to display in the ASP?
C# Code:
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 Code:
Solutions1
Your query returns an integer value, so you want to use ExecuteScalar.
Code Behind
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
Remove
Solutions2
You shouldn't bind the content inside the Label control. You should use the Text property. This should do the job:
Remember that totalApplicants should be a protected variable on your page.
You could also just set the Text property server-side:
while (reader.Read())
{
lblTotalApplicants.Text = reader["TotalApplicants"].ToString();
}