How to read SQL Server COUNT from SqlDataReader in C#?
There are many ways to get the SQL Server Count from SQL Data Reader.First Example
if (sqlDataReader.Read()) {
count = sqlDataReader.GetInt32(0);
}
Second Example
string sql = "SELECT COUNT(*) FROM [DB].[dbo].[tableExample]";
SqlCommand cmd = new SqlComman(sql, connectionString);
int count = (int)cmd.ExecuteScalar();
Third Example
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable results = new DataTable("SearchResults");
lblMsg.Text = results.Rows.Count + " Rows Found.";
Complete Example
SqlConnection conn = new SqlConnection("Database=student;Server=.;user=sa;password=aaaaaaa");
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Cars", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
if (da.Read()) {
count = da.GetInt32(0);
}
}
catch (SqlException ex)
{
// Display any errors...
}
finally
{
// Close connection...
conn.Close();
}