Net-informations.com
SiteMap  | About    

ASP.NET ExecuteScalar

ExecuteScalar method uses to retrieve a single value from a database. The ExecuteScalar() executes SQL statements as well as Stored Procedure and returns the first column of the first row in the result set, or a null reference if the result set is empty.

vb.net

  Dim result As Int32 = Convert.ToInt32(cmd.ExecuteScalar)

C#

  int result = Convert.ToInt32(cmd.ExecuteScalar());

It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.

The following ASP.NET program find number of rows in the author table using ExecuteScalar method.

Default.aspx

  

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
	<title>Untitled Page</title>
</head>
<body>
	<form id="form1" runat="server">
	<div>
		<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
	</div>
	<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
	</form>
</body>
</html>


Click the following links to see full source code

C# Source Code
VB.NET Source Code
default.aspx.cs
default.aspx.vb





net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.