Reputation: 159
I have radio button list that calls a function.
If the function returns true then I want to change the value.
However if the function returns false then I do not want to change the value and keep the original selection value.
Currently it changes the value even when the statement returns false.
Any advice?
ASP Page
<asp:RadioButtonList ID="rblType" runat="server" AutoPostBack="True"
DataSourceID="SqlData" DataTextField="Type"
DataValueField="TypeID">
</asp:RadioButtonList>
VB file
Private selectionvalue As Integer
Protected Sub rblType_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles rblType.SelectedIndexChanged
Dim CheckListValidation As Boolean = CheckListBox()
If CheckListValidation = True Then
selectionvalue = rblType.SelectedItem.Value
Else
rblType.SelectedItem.Value = selectionvalue
End If
End Sub
Function CheckListBox() As Boolean
If lstbox.Items.Count <> "0" Then
If MsgBox("Are you sure you want to change option?", MsgBoxStyle.YesNo, " Change Type") = MsgBoxResult.Yes Then
Return True
Else
Return False
End If
Else
Return True
End If
End Function
Upvotes: 1
Views: 418
Reputation: 14614
The problem is when rblType_SelectedIndexChanged
is executed, the selected item is already changed and the RadioButtonList
doesn't "remember" the previously selected value. You need to keep the previously selected value between postbacks in order to achieve this.
I would suggest using ViewState. Create a property in code behind to represent the ViewState value:
Private Property PreviousSelectedValue() As String
Get
If (ViewState("PreviousSelectedValue") Is Nothing) Then
Return String.Empty
Else
Return ViewState("PreviousSelectedValue").ToString()
End If
End Get
Set(ByVal value As String)
ViewState("PreviousSelectedValue") = value
End Set
End Property
and in rblType_SelectedIndexChanged
:
Protected Sub rblType_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rblType.SelectedIndexChanged
Dim CheckListValidation As Boolean = CheckListBox()
If CheckListValidation = True Then
'save the currently selected value to ViewState
Me.PreviousSelectedValue = rblType.SelectedValue
Else
'get the previously selected value from ViewState
'and change the selected radio button back to the previously selected value
If (Me.PreviousSelectedValue = String.Empty) Then
rblType.ClearSelection()
Else
rblType.SelectedValue = Me.PreviousSelectedValue
End If
End If
End Sub
Upvotes: 3