Home > Data Access in Web Forms > Selecting Information From a Database > Passing Variables to the Select Query
As mentioned in the preceding section, retrieving the correct result set is made possible by providing the input variable to the SQL query statement.
When used within the same page, the variable can be passed directly to the SQL Select statement, as shown in the examples when fetching the list of products that belong to a selected category.
string query = "SELECT ... FROM Products WHERE Type='" + mySelect.Value + "'";
Recall that mySelect is bound to the list of categories, and mySelect.Value returns the category selected by the user.
The selected value can also be obtained and passed to the query statement using the Form collection of the page’s Request object.
string query = "SELECT ... FROM Products WHERE Type='" + Request.Form [ "mySelect" ] + "'";
When the variable will be used in another page ( ex. the product details page ), a variable that references the identifier for the record can be appended to the target URL, and passed as a querystring argument to the requested page ( ex. details_gear.aspx?id=123
).
Because here we are obtaining the record identifiers from a data source bound to a DataList control, the value passed to the id=
parameter would depend on the value of the specified record identifier field ( in this case ProductId ) for each record in the list.
IMPORTANT: The field used as the record identifier must be set ( at the database configuration level ) to accept only unique values, to ensure that no two records ever share the same identifier.
The below snippet shows how this argument is added when constructing the hyperlink to the target page.
<a href='details_gear.aspx?id=<%# Eval ( "ProductId" ) %>’>
Then on the product details page, the variable ( containing the specified ProductID parameter ) can be obtained and passed to the Select statement using the QueryString collection of the page’s Request object.
string query = "SELECT * FROM Products WHERE ProductID='" + Request.QueryString [ "id" ] + "’";
IMPORTANT: If the result set bound to the DataList is expected to change with each request, there is no point in having to store state information in the control across requests. In this case, the control’s EnableViewState property must be set to false to improve overall performance.
Selecting Information From a Database Retrieving Data From Any Source