Search code examples
asp.netcode-behind

How do I move this sample aspx code to aspx.cs (to implement code behind)?


I have a dropdownlist which is populated with data from an SQL db. This is what I might have in the aspx file. How do I move (as much as possible) the code from the aspx file to the aspx.cs file to implement the code behind technique? I mean at least the SELECT portion. Thanks.

<asp:DropDownList ID="DropDownList1" ... runat="server"/>
...
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:Pubs %>"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE    [state] = @state">
<SelectParameters>
<asp:ControlParameter Name="state" ControlID="DropDownList1"  PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>

Solution

  • suppose you are binding a grid with data source SqlDataSource1 then you can catch SelectedIndexChanged event in codebehind and get data to bind the grid like this:

    ASPX file:

    <asp:DropDownList ID="DropDownList1" runat="server" 
             OnSelectedIndexChanged="ddlChanged" />
    

    C# (codebehind):

    protected void ddlChanged(object sender, EventArgs e)
    {
        var cs=..;//get connection string
        using(var con=new SqlConnection(cs))
        {
            using(var com=new SqlCommand(con))
            {
                com.Open();
                com.CommandType = CommandType.Text;
                com.CommandText="SELECT [au_id], [au_lname], [au_fname], [state] 
                     FROM [authors] WHERE [state] = @state";
    
                var state=....;//GET VALUE OF STATE FROM DROPDOWN
                var p = com.Parameters.Add("@state");//set other properties
                p.Value = state;
    
                using(var adptr=new SqlDataAdapter(com))
                {
                    var dtb=new DataTable();
                    adptr.Fill(dtb);
                    grid.DataSource=dtb;
                    grid.DataBind();
                }
            }
        }
    }