Question - What is ExecuteScalar method in ADO.NET?
Answer -
ExecuteScalar Method
The ExecuteScalar method of the SqlCommand object is useful for retrieving a single value from the database. In our example, we need to retrieve the total number of records in the Titles table of the Pubs database. Since the total number of records is a single scalar value, the Execute Scalar method is used. The following is the code and its explanation:
private void frmSqlCommand_Load(object sender, EventArgs e)
{
//Sample 03: Open Database Connection
String con_string = Properties.Settings.Default.ConStrPubs;
pubs_db_connection = new SqlConnection(con_string);
pubs_db_connection.Open();
//Sample 04: Form the Command Object
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select Count(*) as Count from Titles";
cmd.Connection = pubs_db_connection;
//Sample 05: Execute the Command & retrive scalar value
lblTotal.Text = System.Convert.ToString(cmd.ExecuteScalar());
}