2.21. Using Parameterized SQL Statements
Problem
You want to create and execute a SQL statement having parameters that are set dynamically.
Solution
Add parameters to the Command
object’s Parameters collection.
The sample code contains two event handlers and one method:
Form.LoadSets up the sample by creating a
DataTablecontaining all Customers data from Northwind. The default view of the table is bound to aCustomersdata grid on the form. The handler for theCurrentCellChangedevent of the data grid is called to initialize the grid containing Orders with the data for the row selected by default in theCustomersdata grid.DataGrid.CurrentCellChangedGets the
CustomerIDfrom the data grid when the rows selected in the data grid changes and calls theLoadOrderGrid( )method to update the Orders displayed to match the selected Customer.LoadOrderGrid( )This method defines a parameterized SQL statement. A
Commandis built from the statement and the single parameter,@CustomerIDis created and set to thecustomerIdargument passed into the method. TheCommandis used by aDataAdapterto fill aDataTablewith the Orders for the specified Customer. The default view of the table is bound to the Customers data grid on the form.
The C# code is shown in Example 2-30.
Example 2-30. File: UsingParameterizedQueriesForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Data; using System.Data.SqlClient; // Table name constants private const String CUSTOMERS_TABLE ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access