2011-05-26 191 views
1

我創建了一個在線考試頁面,其中包含30個在運行時動態創建的單選按鈕。將onclick事件添加到動態添加的單選按鈕

我將如何獲得每個單選按鈕的click事件並在我的方法中標記它,以檢查下一個問題是否需要跳轉或轉義。

例子:

如果我有問題10,並回答= 「是」,我重定向到第15題,否則轉到下一個問題

回答

0

使用如下語句:

AddHandler radioButton.Click, AddressOf instance.MethodName 

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

+0

改編

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

代碼工作正常而AddressOf允許通過參數的方法。 – spy 2011-05-26 10:53:11

+0

@spy:你不要在這裏指定參數。即使該方法有一些.. – 2011-05-26 10:55:29

+0

@akram - 如果我想通過radiobutton.ID和radiobutton.text – spy 2011-05-26 10:59:52

0

還要考慮使用匿名子(僅VB2010)編寫事件處理程序內嵌從here

您還可以use closures ...

0

HTML代碼 -

<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