我想为动态创建的按钮添加处理。我在Stack上看到的最接近的代码是:asp.net dynamically button with event handler
我有下面的代码,它创建了一个按钮,但我希望每个代码都有一个处理程序。
到目前为止我的代码:
Dim control As LiteralControl
control = New LiteralControl("<div class=""bar-row"">" & _
" <input value=""" & button & """ id=""" & id & """ class=""btnRisk"" type=""submit"">" & _
" <div class=""bar-data"">" & _
" <div class=""bar-inner"">" & _
" <div class=""bar bar-high"" style=""width: " & highPer & "%"">" & high & "</div>" & _
" <div class=""bar bar-med"" style=""width: " & medPer & "%"">" & medium & "</div>" & _
" </div>" & _
" </div>" & _
"</div>")
ChartArea.Controls.Add(control)
重要的部分是:
" <input value=""" & button & """ id=""" & id & """ class=""btnRisk"" type=""submit"">"
我不确定如何修改它。
我需要将按钮ID传递给发件人然后做一些事情,例如
Public Sub Buttons(ByVal sender As Object, ByVal e As EventArgs)
If sender = "1" Then
'do something
End If
If sender ="2" Then
'something else
End If
End Sub
版本2
ChartArea.Controls.Add(New LiteralControl("<div class=""bar-row"">"))
Dim vRiskActive As String = "btnRisk "
If id <> "btnMech" Then vRiskActive = vRiskActive + " risk-inactive"
Dim btnButton As New Button() With {.Text = button, .ID = id, .CssClass = vRiskActive}
AddHandler btnButton.Click, AddressOf button ' here Buttons is your Handler
ChartArea.Controls.Add(btnButton)
If id = "ContentMain_btnMech" Then
ChartArea.Controls.Add(New LiteralControl(" <div class=""bar-data"">" &
" <div class=""bar-inner"">" &
" <div class=""bar bar-high"" style=""width: " & highPer & "%"">" & high & "</div>" &
" <div class=""bar bar-med"" style=""width: " & medPer & "%"">" & medium & "</div>" &
" <div class=""bar bar-low"" style=""width: " & lowhPer & "%"">" & low & "</div>" &
" <div class=""bar bar-na"" style=""width: " & naPer & "%"">" & na & "</div>" &
" </div>" &
" </div>" &
"</div>"))
Else
ChartArea.Controls.Add(New LiteralControl(" <div class=""bar-data"">" &
" <div class=""bar-inner bar-inactive"">" &
" </div>" &
" </div>" &
"</div>"))
End If
值得注意的是子部分......
Public Sub AddChartRow(ByVal button As String, ByVal id As String, ByVal high As Integer, ByVal medium As Integer, ByVal low As Integer, ByVal na As Integer)
答案 0 :(得分:1)
我建议您更改HTML代码并创建一个按钮。创建按钮后,您还可以尝试使用AddHandler来处理按钮事件。
ChartArea.Controls.Add(New LiteralControl("<div class=""bar-row"">"))
Dim btnButton As new Button() With { .Text = button,
.Id = id,
.CssClass = "btnRisk"
}
AddHandler btnButton.Click, AddressOf ButtonsID ' here Buttons is your Handler
ChartArea.Controls.Add(btnButton)
ChartArea.Controls.Add(New LiteralControl(" <div class=""bar-data"">" & _
" <div class=""bar-inner"">" & _
" <div class=""bar bar-high"" style=""width: " & highPer & "%"">" & high & "</div>" & _
" <div class=""bar bar-med"" style=""width: " & medPer & "%"">" & medium & "</div>" & _
" </div>" & _
" </div>" & _
"</div>"))
ChartArea.Controls.Add(control)
有关AdressOf Operator的更多信息,请参阅MSDN