Lesson 7 | Selecting records based on user input |
Objective | Use parameterized queries to select records based on user input values. |
Selecting Records based on User Input
Microsoft replaced Visual InterDev with Visual Web Developer, which was integrated into the Visual Studio suite of tools starting with Visual Studio 2005. Visual Web Developer provided a more modern and robust environment for web development, building on the foundation laid by InterDev. It included enhanced support for ASP.NET (the evolution of Active Server Pages, or ASP), improved code completion, a redesigned user interface, and better integration with database tools.
Additionally, Microsoft introduced Visual Web Developer Express as a free, lightweight version of the toolset, targeting hobbyists and smaller-scale developers. This Express edition offered many of the core features of Visual Web Developer but in a more accessible package. Both Visual Web Developer and its Express variant effectively superseded Visual InterDev, aligning with Microsoft's shift toward the .NET framework and more streamlined, versatile web development tools.
Use Parameterized Queries to select Records based on user input values in SQL-Server 2022
To use "parameterized queries" in "SQL Server 2022" with "Visual Web Developer in Visual Studio 2022", follow these steps:
1. Understanding Parameterized Queries
A parameterized query allows you to pass "user input values" securely to a SQL query while preventing SQL injection attacks.
2. Using Parameterized Queries in ASP.NET with C#
Example: Selecting Records Based on User Input
Assume you have an "Employees" table and you want to select employees based on their last name, which is entered by a user.
Steps:
- Create a Connection to SQL Server
- Use SQL Command with Parameters
- Bind Parameters to User Input Values
- Execute the Query Securely
- Display the Results in a GridView or any UI Component
3. Implementing Parameterized Query in ASP.NET (C#)
Use the `SqlCommand` and `SqlParameter` classes.
C# Code: Using ADO.NET
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class EmployeeSearch : System.Web.UI.Page
{
protected void btnSearch_Click(object sender, EventArgs e)
{
// Get the user input from a TextBox
string lastName = txtLastName.Text.Trim();
// Define SQL connection string (from Web.config)
string connString = WebConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
// SQL query with parameterized input
string query = "SELECT EmployeeID, FirstName, LastName, Email FROM Employees WHERE LastName = @LastName";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
// Add parameter and set value
cmd.Parameters.AddWithValue("@LastName", lastName);
// Open connection
conn.Open();
// Execute query
SqlDataReader reader = cmd.ExecuteReader();
// Bind the results to a GridView (UI Component)
GridView1.DataSource = reader;
GridView1.DataBind();
}
}
}
}
4. Web.config Connection String
Ensure your Web.config file contains the correct connection string:
<configuration>
<connectionStrings>
<add name="MyDBConnection"
connectionString="Server=YOUR_SERVER;Database=YOUR_DATABASE;User Id=YOUR_USER;Password=YOUR_PASSWORD;"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
5. Explanation of the Code
- Prevents SQL Injection: The `@LastName` parameter prevents direct injection attacks.
- Uses `SqlCommand` and `SqlParameter` to pass values safely.
- Binds the data dynamically to a `GridView` in ASP.NET Web Forms.
6. Alternative: Using Entity Framework (EF)
If you prefer Entity Framework, use LINQ with parameters:
using (var db = new MyDbContext())
{
string lastName = txtLastName.Text.Trim();
var employees = db.Employees
.Where(e => e.LastName == lastName)
.ToList();
GridView1.DataSource = employees;
GridView1.DataBind();
}
7. Summary
- Use `SqlCommand` with `Parameters.AddWithValue` to safely pass user input.
- Store the connection string securely in `Web.config`.
- Use Entity Framework for LINQ-based queries if preferred.
This ensures secure, efficient, and scalable database queries in your Visual Web Developer application.
Practically all Web sites today have some level of search capability. The typical scenario includes a search page in which the user selects a search criterion, such as author or title, enters a search term or phrase, and finally clicks a button to submit the search to the Web server.
In the scenario just described, the search criterion and term or phrases are not known at
design time .
Rather, the complete search definition isn't known until
runtime. At runtime, the SQL query is built dynamically after the user submits the search. There are generally two ways to implement runtime dynamic searches.
- Design time: The mode of operation when the application is being written.
- runtime: The mode of operation when the application is running.
- Stored procedures: SQL statements stored in a database
- Parameterized queries: SQL query that uses dynamic parameters
Parameterized Queries
Parameterized queries use a SQL statement with a placeholder. A placeholder is simply a character, such as a question mark, that will be replaced at runtime with the values the user entered. Using placeholders, your application can build SQL queries dynamically at runtime. The following SQL statement shows a placeholder for the book status value.
SELECT ItemNo, Title, Author, Retail FROM BookTable
WHERE Status = ?
You can implement parameterized queries in PHP using several of the database products you read about in the ealier Module on database concepts.
The VirtualBookShelf.com database used in this course is a Microsoft Access database. Unfortunately, PHP doesn't support parameterized queries in Microsoft Access. The simulation in this lesson uses a Microsoft SQL Server database. You use the Recordset DTC to create a parameterized query. The control is bound to a SQL query, which will have one or more placeholders for user-entered values.
The following simulation demonstrates how to create an HTML page that lets the user enter a state abbreviation as the search term.
Using Parameterized Queries
Below is a detailed list of the steps you should have taken to correctly complete the simulation.
- Right-click the Recordset DTC.
- Select Properties from the menu.
- Enter CustRecords in the Name field and click the button to the left of SQL statement.
- The completed SELECT statement is shown below with the missing pieces highlighted.
SELECT CustNo, LName, FName, ADDR1, ADDR2, City, ST, Zip
FROM CustTable WHERE ST = ?
- After completing the statement, click the Implementation tab.
- Deselect Automatically open the Recordset.
- Select the Parameters tab.
- Enter txtState in the Value column and click the Close box.
- The completed script is shown below with the missing pieces highlighted.
<%
dim txtState
txtState = Request("state")
CustRecords.open()
%>
- After completing the script, right-click anywhere in the source editor.
- Select View in browser.
- Type AZ in the Search field.
In the next lesson, you will learn how to use a recordset object within scripts.

