Home

ASP.Net Multiple DropDownList Wrong Code

You have several dropdownlists on your ASP.Net page.

<asp:DropDownList ID="Drop1" AutoPostBack="true" OnSelectedIndexChanged="Drop1Code" runat="server" />
<asp:DropDownList ID="Drop2" AutoPostBack="true" OnSelectedIndexChanged="Drop2Code" runat="server" />
<asp:DropDownList ID="Drop3" AutoPostBack="true" OnSelectedIndexChanged="Drop3Code" runat="server" />

Great! In the code you have 3 voids to process what you want to do

protected void Drop1Code(object sender, EventArgs e)
{
//Do your thing here
}

protected void Drop2Code(object sender, EventArgs e)
{
//Do your thing here
}

protected void Drop3Code(object sender, EventArgs e)
{
//Do your thing here
}

And you run your page. You change one dropdownlist and all is well. BUT BUT if you try another it all goes pete tong, particularly if you've used the back button from another page.

What is happening is this. Say dd1 is changed and as a result of this change you response.redirect to another page. The user then hits the back button. As far as the server is concerned this page is still as is. So you change dd2 and the server looks at the request and says "Errr, like dd1 AND dd2 have changed dude, i'll just do whatever is in the first one then the next" leading to some weird poop.

What I'll do is use some JavaScript and hidden boxes so JavaScript can record what was pressed and tell the server via a button

<asp:DropDownList ID="Drop1" onchange="CatchDrop('Drop1')" runat="server" />
<asp:DropDownList ID="Drop2" onchange="CatchDrop('Drop2')" runat="server" />
<asp:DropDownList ID="Drop3" onchange="CatchDrop('Drop1')" runat="server" />

    <div style="display: none;">
        <asp:TextBox ID="WhichDrop" runat="server" />
        <asp:Button ID="AndyDropChange" OnClick="AnyDropChange" runat="server" />
    </div>

    <script>

function CatchDrop(WhichDrop)
{
    document.getElementById('<%= WhichDrop.ClientID %>').value = WhichDrop
    document.getElementById('<%= AndyDropChange.ClientID %>').click()
}

    </script>

So when we change whichever drop JS notes this drop name in the textbox and then clicks the button. Now we use our code to process what just happened

    protected void AnyDropChange(object sender, EventArgs e)
    {
         switch (WhichDrop.Text)
        {
            case "Drop1":
                Drop1Change();
                break;
            case "Drop2":
                Drop2Change();
                break;
            case "Drop3":
                Drop3Change();
                break;
        }
    }

protected void Drop1Change()
{
//Do your thing
​​​​​​​}

protected void Drop2Change()
{
//Do your thing
​​​​​​​}

protected void Drop3Change()
{
//Do your thing
​​​​​​​}

 

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog