Reputation:
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!
Upvotes: 6
Views: 27446
Reputation: 13692
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
Upvotes: 5
Reputation: 44306
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.
Upvotes: 10
Reputation: 4015
you can try to use
DropDownList2.SelectedItem.Value
instead of
DropDownList2.SelectedItem.Text
Upvotes: 3