ASP.NET - Programmatically adding SqlDataSource and ControlParameter

Programmatically adding SqlDataSource and ControlParameter
SqlDataSourceExample.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    void DropDwonList1_SelectedIndexChanged(object sender, System.EventArgs e) {
        SqlDataSource SqlDataSource2 = new SqlDataSource();
        SqlDataSource2.ID = "SqlDataSource2";
        Page.Controls.Add(SqlDataSource2);
        SqlDataSource2.ConnectionString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
        SqlDataSource2.SelectCommand = "Select ProductID, ProductName, UnitPrice FROM Products WHERE CategoryID=@CategoryID";

        ControlParameter CategoryID = new ControlParameter();
        CategoryID.Name = "CategoryID";
        CategoryID.ControlID = "DropDownList1";
        CategoryID.PropertyName = "SelectedValue";
        
        SqlDataSource2.SelectParameters.Clear();
        SqlDataSource2.SelectParameters.Add(CategoryID);
        SqlDataSource2.Select(DataSourceSelectArguments.Empty);

        GridView1.DataSource = SqlDataSource2;
        GridView1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>asp.net SqlDataSource example: programmatically adding SqlDataSource and ControlParameter</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">SqlDataSource and ControlParameter</h2>
        <asp:SqlDataSource 
            ID="SqlDataSource1"
            runat="server"
            ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            SelectCommand="SELECT CategoryID, CategoryName FROM Categories"
            >
        </asp:SqlDataSource>
        <asp:DropDownList 
            ID="DropDownList1"
            runat="server"
            DataSourceID="SqlDataSource1"
            DataTextField="CategoryName"
            DataValueField="CategoryID"
            OnSelectedIndexChanged="DropDwonList1_SelectedIndexChanged"
            AutoPostBack="true"
            ForeColor="AliceBlue"
            BackColor="CornflowerBlue"
            >
        </asp:DropDownList>
        <asp:GridView 
            ID="GridView1"
            runat="server"
            BackColor="CornflowerBlue"
            ForeColor="AliceBlue"
            HeaderStyle-BackColor="DarkBlue"
            HeaderStyle-ForeColor="White"
            Font-Italic="true"
            GridLines="Vertical"
            BorderColor="LightBlue"
            >
        </asp:GridView>
    </div>
    </form>
</body>
</html>
More asp.net examples