Jun 16, 2010

Update Panel With Dynamic Controls

I am dynamically adding DropDownLists to a table cell. When a DropDownList's selection is changed, I want to update a value ("Label1") on the screen. This value is contained within the Updatepanel ("UP1"). (The DropDownLists are created based on values from a database.) When I create each DropDownList, I also add it to the for the UpdatePanel. This allow the UpdatePanel to be redrawn when the values in the DropDownLists change.

In the example, when I change the selectedvalue in the DropDownList, the "Label1" value on the screen is correctly changed each time but only the 1st, 3rd, 5th, etc. change results in an AsyncPostback. The 2nd, 4th, 6th, etc. results in a full postback. It seems to me that on the 2nd, 4th, etc. occurrence, the UpdatePanel has somehow lost it's (during the last AsyncPostback). When a full postback occurs, everything is reset so that's why it works again the next time.

I know I need to re-add the dynamic trigger to the UpdatePanel, but I don't really know where I should add them.

Thanks for any help you might be able to provide.








Current Value:




Public currentValue As Integer = 0

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim tr As New TableRow
Dim tc As New TableCell
Dim DDL As New DropDownList
DDL.Items.Add(New ListItem("Item #1", 1))
DDL.Items.Add(New ListItem("Item #2", 2))
DDL.ID = "DDL"
DDL.AutoPostBack = True
AddHandler DDL.SelectedIndexChanged, AddressOf SelectionChanged
Dim asyncTrigger As New AsyncPostBackTrigger
asyncTrigger.ControlID = "DDL"
asyncTrigger.EventName = "SelectedIndexChanged"
UP1.Triggers.Add(asyncTrigger)
tc.Controls.Add(DDL)
tr.Cells.Add(tc)
Table1.Rows.Add(tr)
End Sub

Protected Sub SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim thisDDL As DropDownList = CType(sender, DropDownList)
If ViewState("CurrentValue") = "" Then
currentValue = 0
Else
currentValue = CInt(ViewState("CurrentValue"))
End If
currentValue += thisDDL.SelectedValue
ViewState("CurrentValue") = CStr(currentValue)
Label1.Text = CStr(currentValue)
End Sub

No comments:

Post a Comment