Here is the static function which will Generic Data Type to get the scalar value from the query passed to the ExecuteScalar function of the SqlCommand object.
public static T ExecuteScalar<T>(string query, string strConnection)
{
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sc = new SqlCommand();
sc.CommandText = query;
sc.Connection = con;
try
{
con.Open();
return (T)(sc.ExecuteScalar());
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
sc.Dispose();
}
}
{
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sc = new SqlCommand();
sc.CommandText = query;
sc.Connection = con;
try
{
con.Open();
return (T)(sc.ExecuteScalar());
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
con.Dispose();
sc.Dispose();
}
}