//Arquivo de exemplo: ExecuteScalar.aspx.cs
using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Configuration;

public partial class ExecuteScalar : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ConnectionStringSettings getString = WebConfigurationManager.ConnectionStrings["nwind"] as ConnectionStringSettings;
            if (getString != null)
            {
                string sSql = "SELECT Count(CategoryID)AS ContarDeCódigoDaCategoria FROM Categories;";
                using (SqlConnection conn = new SqlConnection(getString.ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand(sSql, conn);
                    try
                    {
                        conn.Open();
                        int i = (int)cmd.ExecuteScalar();
                        lblTotal.Text = "Total de registros: " + i.ToString();
                    }
                    catch (SqlException)
                    {
                        lblTotal.Text = "Erro SQL.";
                    }
                    catch (InvalidOperationException)
                    {
                        lblTotal.Text = "Operação inválida.";
                    }
                    catch (Exception)
                    {
                        lblTotal.Text = "Erro ao executar código.";
                    }
                }
            }
        }
    }
}

