The ExecuteScalar() Method

The ExecuteScalar() method returns the value stored in the first field of the first row of a result set
generated by the command’s SELECT query. This method is usually used to execute a query that
retrieves only a single field, perhaps calculated by a SQL aggregate function such as COUNT() or
SUM().
The following procedure shows how you can get (and write on the page) the number of records
in the Employees table with this approach:
SqlConnection con = new SqlConnection(connectionString);
string sql = " SELECT COUNT(*) FROM Employees ";
SqlCommand cmd = new SqlCommand(sql, con);
// Open the Connection and get the COUNT(*) value.
con.Open();
int numEmployees = (int)cmd.ExecuteScalar();
con.Close();
// Display the information.
HtmlContent.Text += "
Total employees: " +
numEmployees.ToString() + "

";
The code is fairly straightforward, but it’s worth noting that you must cast the returned value to
the proper type because ExecuteScalar() returns an object.

: