locked
Dropdownlist postback always select first item RRS feed

  • Question

  • User1146373797 posted

    Hello, I am new at Asp.net. I hope some experts can help me.

    I have 2 dropdownlist controls (ddl1 and ddl2). When I pick an item from ddl1, it will update ddl2. The problem is when I pick an item in ddl2, it always selects the first item in the list. Is it that the ddl2 autopostback causes the first ddl1 to reload and results the ddl2 to be refreshed also? Or I didn't set something correctly?

    thanks in advance.
    hanvo

     

    <asp:DropDownList ID="ddl1" runat="server" DataSourceID="sqldatasource1" DataTextField="FIELD1" DataValueField="FIELD1" AutoPostBack="True"> 
     <
    /asp:DropDownList>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
                
    ProviderName="<%$  ConnectionStrings:ConnectionString.ProviderName %>"
                
    SelectCommand="SELECT A.FIELD1 FROM TABLE A"> 
     
    </asp:SqlDataSource>

    <asp:DropDownList ID="ddl2" runat="server" DataSourceID="SqlDataSource2 DataTextField="FIELD2" DataValueField="FIELD2" AutoPostBack="true" EnableViewState="true" >
    </asp:DropDownList>
    <asp:SqlDataSource ID="SqlDataSource2" runat="server" 
            
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
                
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
             SelectCommand="SELECT B.FIELD2 FROM TABLE B WHERE B.FIELD2 = :Param1"> 
        <SelectParameters>
         
    <asp:ControlParameter ControlID="ddl1" Type="String" DefaultValue="" Name="Param1" PropertyName="SelectedValue" /> 
        </SelectParameters>
    </asp:SqlDataSource>

     

    Wednesday, March 24, 2010 7:18 PM

Answers

  • User849259894 posted

    Why do have post back on dropdown list 2?  What does it's postback do?

    Your 2nd dropdownlist is bound on SelectedIndexChanged event of the 1st dropdown list.  Choosing 2nd dropdown also causes post back.  May be you are resetting the selected value there? 

    Also what is the EnableStateView property of the parent container of Dropdownlist 1?  If it's value is false then dropdown list 1 is bound to the datasource on every post back.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, March 24, 2010 9:41 PM
  • User-968969268 posted

    Hi, I think on button click event (Postback) it is databinding the dropdown lists again and again.

    Remove the Auto postback=true from second dropdown list (ddl2) if there is no need,

     Use this inside your page Load event


    protected void Page_Load(object sender, EventArgs e)
        {
            //Only dataBind the dropdownlist 1 on page load and not post backs
    
            if (!Page.IsPostback())
    
                 {
                        ddl1.DataBind();
     
                  }       
     
    
        }


    More info on page states in ASP.NET here http://www.15seconds.com/issue/020102.htm



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 25, 2010 6:38 AM
  • User1649254267 posted

    hai,

    ur ddls binds values on every postbak;

    usually we writes this type of code as follwos

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ClearControls();
                BindGrid();
            }
        }

    protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                //code to bind dropdown

            }

        }

    now the dropdown willl bind at firat postback


    MS 

    Mark as Answered if is useful

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 25, 2010 6:50 AM
  • User1146373797 posted

    Yes, I have ddl1.dataind in !Page.IsPostback() block. The only thing that updates ddl3 is  ddl2_SelectedIndexChanged event. I put a breakpoint in ddl2_SelectedIndexChanged to see if other controls raise this event but nothing comes through (except when I select ddl2). I couldn't understand why the ddl2 selectedindex keeps jumping back to 1. Is there something wrong with the viewstates? I have 4 update panels in the same aspx page. It shouldn't be a problem right? Any other ways, that I can track down what's chaging ddl3 SelectedIndex?

     

    Thanks,

    hanvo

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 29, 2010 5:41 PM

All replies

  • User849259894 posted

    Why do have post back on dropdown list 2?  What does it's postback do?

    Your 2nd dropdownlist is bound on SelectedIndexChanged event of the 1st dropdown list.  Choosing 2nd dropdown also causes post back.  May be you are resetting the selected value there? 

    Also what is the EnableStateView property of the parent container of Dropdownlist 1?  If it's value is false then dropdown list 1 is bound to the datasource on every post back.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, March 24, 2010 9:41 PM
  • User1146373797 posted

    Actually, I have 3 dropdownlists inside an UpdatePanel. The 2nd one will update the 3rd one. The 3rd one also has the same issue. I Just listed 2 controls for demonstration.

    I don' t have any codebehind to reset the selected value on 2nd ddl. The 3rd ddl has AutoPostBack=False and EnableViewState=True but when I click a button to add the selected values, the 3rd ddl also selects its first value before I can capture the right value. 

    I did try to set the first ddl to have EnableViewState=True but still doesn't fix the issue.

    Does it have anything to do with the way I select records in SQLDataSource? The data in the table doesn't change.

     

     

      

    Thursday, March 25, 2010 4:18 AM
  • User-968969268 posted

    Hi, I think on button click event (Postback) it is databinding the dropdown lists again and again.

    Remove the Auto postback=true from second dropdown list (ddl2) if there is no need,

     Use this inside your page Load event


    protected void Page_Load(object sender, EventArgs e)
        {
            //Only dataBind the dropdownlist 1 on page load and not post backs
    
            if (!Page.IsPostback())
    
                 {
                        ddl1.DataBind();
     
                  }       
     
    
        }


    More info on page states in ASP.NET here http://www.15seconds.com/issue/020102.htm



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 25, 2010 6:38 AM
  • User1649254267 posted

    hai,

    ur ddls binds values on every postbak;

    usually we writes this type of code as follwos

    protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ClearControls();
                BindGrid();
            }
        }

    protected void Page_Load(object sender, EventArgs e)

        {

            if (!IsPostBack)

            {

                //code to bind dropdown

            }

        }

    now the dropdown willl bind at firat postback


    MS 

    Mark as Answered if is useful

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 25, 2010 6:50 AM
  • User1146373797 posted

    I couldn't get the ddls to work. I just couldn't understand the behaviors. As you guys mentioned that the postbacks would refresh all controls since they are bound together. I changed to populate items in the ddls via coding instead of SQLDataSource.  I think I am ok for now. Thanks again.

    hanvo

    Thursday, March 25, 2010 7:04 PM
  • User-968969268 posted

    It is the same thing, even if you bind the dropdown lists through code you have to put the ADO.Net code inside a if(!PostBack)


    Friday, March 26, 2010 12:41 AM
  • User1146373797 posted

    You are right. It's the same thing. I did put the first ddl in the !postback but I have to put the 2nd ddl outside. The reason is that the first ddl will update the 2nd ddl and the 2nd ddl will update the third one. Right now, 1st and 2nd are ok. Only the 3rd one keeps being resets to SelectedIndex=1.  

    Maybe this is not the right approach but I have seen websites that allow users to select via multiple ddls. (Car Make > Model > Engine....)  

    What are other ways to accomplish these chaining ddls? postback via Javascript?

    Thanks,

    hanvo

    Friday, March 26, 2010 7:22 PM
  • User-968969268 posted

    For binding through code behind.

    1. Bind the 1st dropdown list (ddl1) on page load event inside a (!PostBack()) block.
    2. Bind the 2nd dropdown list (ddl2) on ddl1's SelectedIndexChanged event and not on pageload()
    3. Bind the 3rd dropdownlist (ddl3) on drop ddl2's selectedIndexChanged event

    Alternatively, you may use sql datasource's control parameter property & set the autopost back properties of dropdown lists to true()

         Just define sql datasource parameters for the 2nd & 3rd ddl's query

    For e.g

                       DDL1 query => Select * from tableA

                       DDL2 query => Select * from tableB where id=@id    (Bind this parameter with your ddl1 selected value)

    More on control parameters here http://msdn.microsoft.com/en-us/library/z72eefad.aspx

    You can set the parameters visually through sql datasource's select statement property.


    Saturday, March 27, 2010 12:15 AM
  • User1146373797 posted

    Mike,

    Originally, I bound the controls via sql datasource and it didn't work. That was why I changed to bind using codebehind and it's exactly the same as you suggested.

    For some reasons, if something is posting back, the ddl3 always select the index=1. The only thing that can cause ddl3 to change is ddl2 but I have EnableViewState=True on ddl2.

    It doesn't just make sense to me. I need to understand more abou the page load cycles.

    Thanks,

    hanvo

     

     

     

    Sunday, March 28, 2010 8:05 PM
  • User-968969268 posted

    Hi, It should work either way.

    ddl1 triggers -> ddl2 triggers -> ddl3

    So on postback ddl1 binds again it will cause you to loose your selection in ddl3. So, put ddl1 databind in

    if(!Page.IsPostBack())

    {

    ddl1.DataBind();

    }

    Monday, March 29, 2010 1:35 AM
  • User1146373797 posted

    Yes, I have ddl1.dataind in !Page.IsPostback() block. The only thing that updates ddl3 is  ddl2_SelectedIndexChanged event. I put a breakpoint in ddl2_SelectedIndexChanged to see if other controls raise this event but nothing comes through (except when I select ddl2). I couldn't understand why the ddl2 selectedindex keeps jumping back to 1. Is there something wrong with the viewstates? I have 4 update panels in the same aspx page. It shouldn't be a problem right? Any other ways, that I can track down what's chaging ddl3 SelectedIndex?

     

    Thanks,

    hanvo

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, March 29, 2010 5:41 PM
  • User-968969268 posted

    Hi check the following example. I have 3 dropdown lists inside a single update panel using Northwind database.

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ddlCategories.DataBind();
            }
            
        }
    
        protected void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCategories.SelectedIndex == 0)
            {
                ddlProducts.Items.Clear();
                ddlSales.Items.Clear();
            }
        }
        protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e)
        {
            
        }

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
    
    <%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        Namespace="System.Web.UI" TagPrefix="asp" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.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:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <asp:DropDownList ID="ddlCategories" runat="server" AutoPostBack="True" DataSourceID="sdsCategories"
                                    DataTextField="CategoryName" DataValueField="CategoryID" AppendDataBoundItems="True" OnSelectedIndexChanged="ddlCategories_SelectedIndexChanged">
                        <asp:ListItem Text="- Select a Category -" Value=""></asp:ListItem>
                    </asp:DropDownList><asp:SqlDataSource ID="sdsCategories" runat="server" ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
                                    SelectCommand="SELECT [CategoryID], [CategoryName] FROM [Categories] ORDER BY [CategoryName]">
                    </asp:SqlDataSource>
                                <asp:DropDownList ID="ddlProducts" runat="server" AutoPostBack="True" DataSourceID="sdsProducts" DataTextField="ProductName" DataValueField="ProductID" OnSelectedIndexChanged="ddlProducts_SelectedIndexChanged">
                                
                                
                                </asp:DropDownList><asp:SqlDataSource ID="sdsProducts" runat="server" ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
                                    SelectCommand="SELECT [ProductID], [ProductName], [CategoryID] FROM [Products] WHERE ([CategoryID] = @CategoryID)">
                                    <SelectParameters>
                                        <asp:ControlParameter ControlID="ddlCategories" Name="CategoryID" PropertyName="SelectedValue"
                                            Type="Int32" />
                                    </SelectParameters>
                                </asp:SqlDataSource><asp:DropDownList ID="ddlSales" runat="server" AutoPostBack="True" DataSourceID="sdsOrders" DataTextField="CustomerName" DataValueField="Address">
                                </asp:DropDownList><asp:SqlDataSource ID="sdsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>" SelectCommand="SELECT [ProductID], [CustomerName], [Address] FROM [Invoices] WHERE ([ProductID] = @ProductID)">
                                    <SelectParameters>
                                        <asp:ControlParameter ControlID="ddlProducts" Name="ProductID" PropertyName="SelectedValue"
                                            Type="Int32" />
                                    </SelectParameters>
                                </asp:SqlDataSource>
                </ContentTemplate>
            </asp:UpdatePanel>
            <br />
            <br />
             <br />
        
        </div>
        </form>
    </body>
    </html>
    



    Thursday, April 1, 2010 1:46 AM