时间:2011-05-26 10:38:44

标签: asp.net vb.net

我正在创建一个在线考试页面,其中包含30个在运行时动态创建的单选按钮。

如何获取每个单选按钮的click事件并在我的方法中标记它,我将检查下一个问题是否需要跳转或逃脱。

示例:

如果我在问题10并回答=“是”,请将我重定向到问题15,否则转到下一个问题

3 个答案:

答案 0 :(得分:0)

使用以下声明:

AddHandler radioButton.Click, AddressOf instance.MethodName  

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

答案 1 :(得分:0)

还可以考虑使用匿名子(仅限VB2010)来编写内联事件处理程序

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

改编自here

您还可以use closures ...

答案 2 :(得分:0)

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代码 -

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