Database Reference
In-Depth Information
Listing 13-2. CommandScalar.cs
using System.Data.SqlClient;
private void btnRowCount_Click(object sender, EventArgs e)
{
// Create connection
SqlConnection conn = new SqlConnection(@"server = .\sql2012;
integrated security = true; database = AdventureWorks");
// Create Scalar query
string sql = @"select count(*)
from Production.Product";
// Create command
SqlCommand cmd = new SqlCommand(sql, conn);
txtScalar.AppendText("Command created and connected.\n");
try
{
// Open connection
conn.Open();
txtScalar.AppendText("Number of Product is :");
// Execute Scalar query with ExecuteScalar method
txtScalar.AppendText(cmd.ExecuteScalar().ToString());
txtScalar.AppendText("\n");
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
txtScalar.AppendText("Connection Closed.");
}
}
8. To set the CommandScalar form as the start-up form, modify the Program.cs
statement:
Application.Run(new CommandText ());
to appear as:
Application.Run(new CommandScalar());
Build the project, and run it by pressing Ctrl+F5.
Search WWH ::




Custom Search