ExecuteScalar() in ADO.NET using Asp.net with Example

In our previous article we discuss about ExecuteNonQuery() with example in asp.net, In which we already describe about ADO.NET operations. In this article we come with total diff approach then ExecuteNonQuery(). ExecuteNonQuery() will use to check database changes while T-SQL Statements. and ExecuteScalar() will get first column first row value. We will discuss difference between ExecuteScalar() and ExecuteNonQuery() and ExecuteReader() in our next article.

ExecuteScalar()
ExecuteScalar() method of SqlCommand Class. ExecuteScalar() method will return only First Column First Row (you can also take it as first row first column , both are same) value from whole datatable.

As we Describe in ExecuteNonQuery() Example we are taking same data structure. We will perform Select operation to work will ExecuteScalar() method. 

ExecuteScalar() Example in Ado.net


Database Structure for our example

Column NameData Type
IDint(Primary Key)
First Namevarchar(50)
Last Namevarchar(50)
Cityvarchar(30)
EmailIDvarchar(100)

Sql Query
CREATE TABLE Sample(
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [FirstName] [varchar](50) NULL,
 [LastName] [varchar](50) NULL,
 [City] [varchar](30) NULL,
 [EmailID] [varchar](100) NULL)
We have Inserted data in our table
ExecuteScalar() Example in asp.net
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Button ID="btnSelect" runat="server" OnClick="btnSelect_Click" Text="Execute" /><br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

Default.aspx.cs
protected void btnSelect_Click(object sender, EventArgs e)
    {
        string ConnectionString = "Write your ConnectionString Here";
        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            con.Open();
            string Query = "select FirstName, LastName, City, EmailID from Sample";
            SqlCommand cmd = new SqlCommand(Query, con);
            string retmsg = cmd.ExecuteScalar().ToString();// use of ExecuteScalar()
            if (!string.IsNullOrEmpty(retmsg))
            {
                lblMessage.Text = retmsg;
            }
            else
            {
                lblMessage.Text = "No Record Found";
            }
        }
    }
Demo

Download Sample Code