Reputation: 881
I can't get the selected value of a programmatically generated list of items:
Protected Sub ddlMMMYY2_PreRender(ByVal sender As Object, ByVal e
As System.EventArgs) Handles ddlMMMYY2.PreRender
If Not Page.IsPostBack Then
'Value= 08.2009 Text=Aug 09
Dim d As Date
d = Now
Dim myDay As Date
Dim myDayStr As String
Dim myDayValue As String
Dim i As Integer
For i = 0 To 15
myDay = d.AddMonths(i)
myDayValue = myDay.ToString("MM.yyyy")
myDayStr = myDay.ToString("MMMM yyyy")
Dim item As ListItem = New ListItem
item.Text = myDayStr
item.Value = myDayValue
Me.ddlMMMYY2.Items.Add(item)
Next
If Not Request.QueryString("Abreise") Is Nothing Then
Dim Anreise As String = Request.QueryString("Abreise")
Dim myArray As Array
myArray = Split(Anreise, ".")
Me.ddlMMMYY2.Items.FindByValue(myArray(1).ToString & "."
& myArray(2).ToString).Selected = True
End If
End If
End Sub
If I try to get a value from a static DropDownList
, <asp:listitem>
works.
What can I do?
Upvotes: 0
Views: 1899
Reputation: 6962
Make sure ViewState is enabled for the DropDownList. You may need to rebind the DropDownList before you can get the selected value.
and as Michael Edwards said - ViewState has already been saved before the PreRender event is raised.
Upvotes: 1
Reputation: 6528
You need to add the items to the dropdown box using either by overriding the CreateChildChild controls or override the OnInit method. Adding the items to the list using PreRender means that it is too late for the view state to connect the list items that you entered with the value returned from the browser.
Also if you use either the Init method or CreateChildControls the values you enter into the dropdown list are saved by the view state so wrap the hole thing in a if(!IsPostback)
Hope that makes sense :-)
Upvotes: 1