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() 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)

Sql Query
 [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
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
    <asp:Button ID="btnSelect" runat="server" OnClick="btnSelect_Click" Text="Execute" /><br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label>
protected void btnSelect_Click(object sender, EventArgs e)
        string ConnectionString = "Write your ConnectionString Here";
        using (SqlConnection con = new SqlConnection(ConnectionString))
            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;
                lblMessage.Text = "No Record Found";

Download Sample Code


Popular posts from this blog

12 opensource and free asp.net MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in asp.net