vb.net 动态生成的控件,事件也动态加,怎么做呢?
'把图片的声明放在外面,类里面过程外面,而且要用As,不然等会儿没法用Dim myPicture As New System.Windows.Forms.PictureBox()'动态生成的控件,加一行Private Sub UserControl1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.LoadMe.Panel3.Controls.Add(myPicture)myPicture.Size =New System.Drawing.Size(115, 160)myPicture.TabStop =FalsemyPicture.Name ="p"myPicture.Cursor = Cursors.HandAddHandler myPicture.Click, AddressOf mypic_Click '添加事件AddHandler returnid, AddressOf idReturned '绑定事件和过程End Sub'再来个事件,放在声明的地方,就是类里面、过程外面Private Event returnid(ByVal id As String) '这个事件可以传递值哦~'普通的单击事件Private Sub mypic_Click()RaiseEvent returnid(myPicture.Name)End Sub'会传值的事件过程Private Sub idReturned(ByVal id As String)Dim bookInfo As New BookInfobookInfo.Show()Me.Parent.Enabled = False'用id变量做点什么吧End Sub如果要改事件的签名(参数一类的)的话,得重写控件。你可以这样自己弄一个事件。
Private WithEvents NewTextBox As TextBox
'通过使用WithEvents关键字声明一个对象变量为新的命令按钮
Private Sub Command1_Click()
If NewTextBox Is Nothing Then
Set NewTextBox = Controls.Add("VB.TextBox", "cmdNew", Form1)
NewTextBox.Move 200, 200
NewTextBox.Width = Form1.Width - 450
NewTextBox.Height = Form1.Height - 1400
NewTextBox.Visible = True
End If
End Sub
Private Sub Command2_Click()
If NewTextBox Is Nothing Then
Exit Sub
Else
Controls.Remove NewTextBox
Set NewTextBox = Nothing
End If
End Sub
你需要的应该是反射,类似如下,我测试通过的:
Imports System.Reflection
Public Class Form1
Public Sub MMMToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles MMMToolStripMenuItem.Click
MsgBox("menu click")
End Sub
'在按钮事件处理里面通过反射名称调用相应菜单事件
Public Sub CallEventMethod(sender As Object, e As EventArgs)
Dim b As Button = sender '获取点击的按钮
'拼接菜单事件名称
Dim MethodName As String = b.Name & "ToolStripMenuItem_Click"
Dim t As Type = Me.GetType
Dim m As MethodInfo = t.GetMethod(MethodName)
'反射方法
m.Invoke(Me, New Object() {Nothing, Nothing})
End Sub
'动态生成了按钮
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim btn As New Button
btn.Location = New Point(100, 100)
btn.Name = "MMM" '关键
btn.Text = "MMM"
'注册事件
AddHandler btn.Click, AddressOf Me.CallEventMethod
Me.Controls.Add(btn)
End Sub
End Class
你不是会绑定事件吗?
vb.net 动态生成的控件,事件也动态加,怎么做呢?视频
相关评论: