tags:

views:

1017

answers:

3

I have a simple dropdownlist(ffg)...

<asp:DropDownList   ID="DropDownList2" runat="server"  AutoPostBack="true" BackColor="LightSteelBlue" Font-Size="X-Small"
    OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged1"  Style="z-index: 102; left: 37px; position: absolute; top: 85px" Width="331px"
    </asp:DropDownList>

which I bind data to usind the onpageload event...

DropDownList2.DataSource = td.DataSet
DropDownList2.DataSource = td
DropDownList2.DataTextField = td.Columns("Name").ColumnName.ToString
DropDownList2.DataValueField = td.Columns("VendorCode").ColumnName.ToString
DropDownList2.DataBind()

and an onleselectedindexchaged event where I try to retreive the new value like this...

Protected Sub DropDownList2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList2.TextChanged
        Dim url As String = "sp_menu.aspx?sp=" & DropDownList2.SelectedValue
        Session.Remove("sp")
        Session("sp") = DropDownList2.SelectedValue
        Session("spnm") = DropDownList2.SelectedItem.Text & " (" & DropDownList2.Text & ")"
        Response.Redirect(url)
    End Sub

But it always brings the first value no matter which one is clicked on the dropdownlist. Please help!

A: 

you can try to use

DropDownList2.SelectedItem.Value

instead of

DropDownList2.SelectedItem.Text
darkdog
+4  A: 

Ok... a few things...

First DropDownList2_TextChanged isn't wired to your DropDownList so I can't see how that event would ever fire unless you're doing the wireup in your codebehind

Second

You say this code here

DropDownList2.DataSource = td.DataSet
DropDownList2.DataSource = td
DropDownList2.DataTextField = td.Columns("Name").ColumnName.ToString
DropDownList2.DataValueField = td.Columns("VendorCode").ColumnName.ToString
DropDownList2.DataBind()

is in your PageLoad event. Have you wrapped it in an If Not IsPostBack, because if not, then you'll rebind every time, and lose your previous selection.

Eoin Campbell
I did not wrap it in If Not IsPostBack because I redirect the user to a different page when they choose an item...I will try to wrap it and then get back to you.
Hi. Thank you very much for your help. It seems I needed to wrap it in an If Not IsPostBack. Now it works perfectly. I was not aware that the post back happens even if a event has occured (in which a user is redirected to a different page.) Cool...
No Problems. Logically, what's happening is, the selected index changed, that fires some javascript with a __doPostBack to the same page. The page_load event fires, then you're SelectedIndexChanged event fires, and THEN you redirect to the next page.
Eoin Campbell
+1  A: 

When you're databinding in Page_Load, you're essentially also resetting the selecteditem.

You should wrap whatever bindingcode that exists in Page_Load inside an if(!IsPostBack) block.

EDIT: ...or If Not IsPostBack Then ... End If in VB.NET

Arjan Einbu