In this article I will explain with an example, how to dynamically change SelectCommand of SqlDataSource at runtime in ASP.Net using C# and VB.Net.
In order to change the SelectCommand of SqlDataSource at runtime, the SqlDataSource needs to be accessed programmatically from code behind in ASP.Net.

Dynamically change SelectCommand of SqlDataSource at runtime in ASP.Net

For this article I have made use Customers table of Microsoft Northwind Database. You can download the database using the link below.
HTML Markup
The HTML Markup contains the following GridView .
<asp:GridView ID="GridView1" runat="server" CssClass="Grid" AutoGenerateColumns="false">
        <asp:BoundField DataField="ContactName" HeaderText="Customer Name" />
        <asp:BoundField DataField="City" HeaderText="City" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
        <asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />

Connection String
I have added the following connection string in the Web.Config file.
    <addname="conString"connectionString="Data Source=.\SQL2005;Initial Catalog=northwind;User id = user;password=xxx"/>


Binding the ASP.Net GridView with SqlDataSource Programmatically
In the below code I am binding the ASP.Net GridView from code using SqlDataSource. The SqlDataSource is dynamically added to the page at runtime in the Page_Load event of the ASP.Net page.
The following parameters of the SqlDataSource need to be set.
1. ConnectionString – ConnectionString to the Northwind Database.
2. SelectCommand – The SQL Query you need to execute.
protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)
        SqlDataSource SqlDataSource1 = new SqlDataSource();
        SqlDataSource1.ID = "SqlDataSource1";
        SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
        SqlDataSource1.SelectCommand = "SELECT top 10 ContactName, City, Country, PostalCode from Customers";
        GridView1.DataSource = SqlDataSource1;
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim SqlDataSource1 As New SqlDataSource()
        SqlDataSource1.ID = "SqlDataSource1"
        SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("conString").ConnectionString
        SqlDataSource1.SelectCommand = "SELECT top 10 ContactName, City, Country, PostalCode from Customers"
        GridView1.DataSource = SqlDataSource1
    End If
End Sub


You can download the complete code in VB.Net and C# using the download link provided below.