Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (11.97 KB, 2 trang )
[ Team LiB ]
Recipe 10.5 Counting Records
Problem
You want to determine how many rows that meet certain criteria are in a table.
Solution
Use the ExecuteScalar( ) method of the Command object to determine the number of
records in the table.
The sample code executes the COUNT function on the results of a query returning rows
from the Orders table in the Northwind sample database, where the rows match a user-
specified CustomerID.
The C# code is shown in Example 10-5
.
Example 10-5. File: CountRecordForm.cs
// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
// . . .
// Create the connection.
SqlConnection conn = new SqlConnection(
ConfigurationSettings.AppSettings["Sql_ConnectString"]);
// Build the query to count, including CustomerID criteria if specified.
String selectText = "SELECT COUNT(*) FROM Orders";
if(customerIdTextBox.Text.Trim( ) != "")
selectText += " WHERE CustomerId='" + customerIdTextBox.Text + "'";