How to count total number of records present in the SQL server table using ASP.net?
Are you looking for how to count total number of records present in the SQL server table using ASP.net? Then this code snippet will help you. I have used SQL server 2008 as a back end and ASP.net as a front end.
Description:
If you are looking for the total number of records present in the SQL server table then following code will be used.
It can also be used when you want to auto-increment or auto-decrement any value by getting total record count.
public int CalculateTotalRecords()
{
int records_total = 0;
string connectionString = "Data Source=your_server_name\\your_sql_server_instancename;Initial Catalog=your_databasename;Integrated Security=True;";
SqlConnection sqlConnection = new SqlConnection(connectionString);
DataSet myObj = new DataSet();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "Select count(columnname) As TotalRec FROM tablename";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(myObj);
if (myObj.Tables.Count > 0)
{
foreach (DataRow dr in myObj.Tables[0].Rows)
{
records_total = Convert.ToInt32(dr["TotalRec"].ToString());
}
}
return records_total;
}
Call above function in page load method
protected void Page_Load(object sender, EventArgs e)
{
int totalnumber = CalculateTotalRecords();
}