The ExecuteScalar() in C# SqlCommand Object is using for retrieve a single value from Database after the execution of the SQL Statement. The ExecuteScalar() executes SQL statements as well as Stored Procedure and returned a scalar value on first column of first row in the returned Result Set.
If the Result Set contains more than one columns or rows , it will take only the value of first column of the first row, and all other values will ignore. If the Result Set is empty it will return a NULL reference.
It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statement Here like Select Count(*) from product";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
cnn.Close();
MessageBox.Show (" No. of Rows " + count);
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}