<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SqlInjectionCorrected" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox id="txtID" runat="server">ALFKI' OR '1'='1</asp:TextBox>
<asp:Label id="Label1" runat="server">Enter Customer ID:</asp:Label>
<asp:Button id="cmdGetRecords" runat="server" Text="Get Records" OnClick="cmdGetRecords_Click"></asp:Button>
<asp:GridView id="GridView1" runat="server" Width="392px" Height="123px"></asp:GridView>
</div>
</form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class SqlInjectionCorrected : System.Web.UI.Page
{
protected void cmdGetRecords_Click(object sender, System.EventArgs e)
{
string connectionString = "Data Source=localhost;Initial Catalog=Northwind;" +
"Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
string sql =
"SELECT Orders.CustomerID, Orders.OrderID, COUNT(UnitPrice) AS Items, " +
"SUM(UnitPrice * Quantity) AS Total FROM Orders " +
"INNER JOIN [Order Details] " +
"ON Orders.OrderID = [Order Details].OrderID " +
"WHERE Orders.CustomerID = @CustID " +
"GROUP BY Orders.OrderID, Orders.CustomerID";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("@CustID", txtID.Text);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
con.Close();
}
}