Executescalar in asp.net

Description:-

In this article we will see about Execute Scalar in Webpage. How to use it and to get data by using it in code behind. Using this we can get one data at a time from database like if we want total country from database then we can use Scalar function for reading single reading data from database. It use aggregate function to read it and get from database. Here is the demo example to get total country from database and display it on your webpage.

Create Table:-

CREATE TABLE [dbo].[Country](
 [CountryID] [bigint] IDENTITY(1,1)NOTNULL,
 [CountryName] [varchar](50)NULL,
CONSTRAINT [PK_Country] PRIMARYKEYCLUSTERED
(
 [CountryID] ASC
)WITH (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON [PRIMARY]
)ON [PRIMARY]

GO

Default.aspx:-

<div>
 <asp:Button ID="Button1" runat="server" Text="Count Country" OnClick="Button1_Click"/>
</div>
<asp:Label ID="Label1" runat="server"Text=""></asp:Label>

Default.aspx.cs:-

protected void Button1_Click(object sender, System.EventArgs e)
{
  string connectionString = ConfigurationManager.ConnectionStrings["DBCS_New"].ToString();
  SqlConnection connection = new SqlConnection(connectionString);
  string sql = "select count(*) from Country";
  try
  {
    connection.Open();
    SqlCommand cmd = new SqlCommand(sql, connection);
    int result = Convert.ToInt32(cmd.ExecuteScalar());
    connection.Close();
    Label1.Text = "Number of Countries - " + result;
  }
  catch (Exception ex)
  {
    Label1.Text = "Error in ExecuteScalar " + ex.ToString();
  }
}

Related Posts

Previous
Next Post »

1 comments:

comments

Thanks for comments.....