开发者

Add onclick event to the radio button that added dynamically

I'm creating an online exam page with 30 radiobuttons that are created dynamically at runtime.

How will I get the click event of each radiobutton and tag it in my method that I will check if the next question is need to be jump or escape.

Example:

If I'm in question 10 and answer = "Yes", red开发者_Go百科irect me to Question 15, else go to the next question


HTML code-

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Panel ID="RadioButtonsPanel" runat="server" />
    </form>

</body>
</html>

VB Code-

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    '   Add each radio button 
    AddNewRaduiButton("MyRadio1")
    AddNewRaduiButton("MyRadio2")
    AddNewRaduiButton("MyRadio3")
    AddNewRaduiButton("MyRadio4")
End Sub

Private Sub AddNewRaduiButton(ByVal name As String)

    '   Create a new radio button 
    Dim MyRadioButton As New RadioButton

    With MyRadioButton
        .ID = name
        .AutoPostBack = True
        .Text = String.Format("Radio Button - '{0}'", name)
    End With

    '   Add the click event to go to the sub "MyRadioButton_CheckedChanged"
    AddHandler MyRadioButton.CheckedChanged, AddressOf MyRadioButton_CheckedChanged

    Page.FindControl("RadioButtonsPanel").Controls.Add(MyRadioButton)
End Sub


Protected Sub MyRadioButton_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

    '   Convert the Sender object into a radio button 
    Dim ClickedRadioButton As RadioButton = DirectCast(sender, RadioButton)

    '   Display the radio button name
    MsgBox(String.Format("Radio Button {0} has been Updated!", ClickedRadioButton.ID))

End Sub


Use the following statement:

AddHandler radioButton.Click, AddressOf instance.MethodName  

Refer to How to: Dynamically Bind Event Handlers at Run Time in ASP.NET Web Pages


Also consider using an anonymous sub (VB2010 only) to write the event handler inline

AddHandler radioButton.Click,
    Sub(s As Object, e As EventArgs)
        MessageBox.Show("Awesome!")            
    End Sub

Adapted from here

You can also use closures...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜