user544079
user544079

Reputation: 16639

Updating image based on drop down list selection in asp.net

I have a drop down list defined as

<asp:DropDownList ID="ddl1" runat="server"    OnSelectedIndexChanged="ddl1_SelectedIndexChanged" style="width: 107px">
        <asp:ListItem Selected="True" Text="Select a value" Value="select">Select a value</asp:ListItem>
        <asp:ListItem Value="p1">Image 1</asp:ListItem>
        <asp:ListItem Value="p2">Image 2</asp:ListItem>
        <asp:ListItem Value="p3">Image 3</asp:ListItem>
</asp:DropDownList>
<div id="img">
  <asp:Image ID="image1" runat="server"  Width="100"/>
</div>

On changing the selection the event is defined in the code-behind as

protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
    string i = ddl1.SelectedValue;
    switch (i)
    {
        case "p1":
            image1.ImageUrl = "img/p1.jpg";
            break;
        case "p2":
            image1.ImageUrl = "img/p2.jpg";
            break;
        case "p3":
            image1.ImageUrl = "img/p3.jpg";
            break;
        default "select":
            image1.ImageUrl = "";
            break;
    }
}

However, this does not seem to pick the images.

Upvotes: 0

Views: 3468

Answers (1)

gzaxx
gzaxx

Reputation: 17600

.SelectedValue is only used when list is databinded! So this is why no image is selected.. Loooking at MSDN proofs me wrong http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue.aspx

Change it to this:

string i = ddl1.SelectedItem.Value;

and it will work :).

Upvotes: 1

Related Questions