Using ExecuteScalar to Populate a Variable in C#

Using ExecuteScalar to Populate a Variable in C#

After many attempts and various and sundry internet searchings, I have finally have properly working code to display the result of a scalar query in tSQL using asp.net C#.

I had to add the reference to System.Configuration in Visual Studio.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;

Then I have this code in the PageLoad event of code behind:

int addcount; //variable to hold my result
string strConnection = ConfigurationManager.ConnectionStrings[“addressesConnectionString”].ConnectionString; // my connection string defined in web.config
string strSelect = @”SELECT COUNT(AddressID) FROM mainaddr”; //my query returning a single result
SqlConnection con = new SqlConnection(strConnection); 
SqlCommand cmd = new SqlCommand(); 
cmd.Connection = con; 
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSelect;

con.Open();
addcount = Convert.ToInt16(cmd.ExecuteScalar()); //running the scalar query and capturing the result
con.Close();

if (addcount >= 1)
{
lblCount.Text = “We currently have ” + addcount.ToString() + ” addresses.”; //actually setting the label text to the result of the scalar query
}

I hope this helps someone and saves you a little bit of time!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.