Programmatically adding a SqlDataSource control to the Page
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script runat="server">
void lstCategories_SelectedIndexChanged(Object sender, EventArgs e)
{
SqlDataSource productsSource = new SqlDataSource();
productsSource.ID = "productsSource";
Page.Controls.Add(productsSource);
productsSource.ConnectionString = WebConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
productsSource.SelectCommand = "GetProductsByCategoryID";
productsSource.SelectCommandType = SqlDataSourceCommandType.StoredProcedure;
ControlParameter categoryIdParam = new ControlParameter();
categoryIdParam.ControlID = "lstCategories";
categoryIdParam.Name = "ProductSubcategoryID";
categoryIdParam.PropertyName = "SelectedValue";
productsSource.SelectParameters.Clear();
productsSource.SelectParameters.Add(categoryIdParam);
productsSource.Select(DataSourceSelectArguments.Empty);
GridView1.DataSource = productsSource;
GridView1.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Programmatically adding a SqlDataSource control to the Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="categoriesSource" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:AdventureWorks %>"
SelectCommand="GetProductSubCategories"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
Categories:
<asp:DropDownList runat="server"
DataSourceID="categoriesSource"
DataValueField="ProductSubcategoryID"
OnSelectedIndexChanged="lstCategories_SelectedIndexChanged"
DataTextField="Name"
AutoPostBack="true"
ID="lstCategories" />
<asp:GridView ID="GridView1" runat="server"
HeaderStyle-HorizontalAlign="Center"
HeaderStyle-Font-Bold="True"
HeaderStyle-BackColor="blue"
HeaderStyle-ForeColor="White" />
</div>
</form>
</body>
</html>
Related examples in the same category