【发布时间】:2015-04-09 23:29:18
【问题描述】:
我正在创建一些选项卡,我需要做两件我无法开始工作的事情。我需要AddHandler 来获得Textbox.Keypress 事件和Button.Click 事件。我可以让这些东西在 tabcontrol 之外工作,但不能在里面。
在下面的示例中,我的文本框和按钮从一个选项卡到另一个具有相同的名称,我认为这可能是我的问题,但即使在选项卡之间更改名称也不起作用。我认为我需要在 AddHandler 部分中更具体地提供选项卡名称和控制权。我的真实代码中有一个逻辑允许我为每个选项卡面板和控件提供唯一的名称,但我无法让简单的部分工作。
我留下了一些我尝试过的评论,但我尝试了很多其他的东西。
Public Class Form1
Public Sub addTab(tabPageName As String)
Dim tabpage As New TabPage
tabpage.Text = tabPageName
tabpage.Name = "tabPage1" 'real code has logic to make sure names are unique
Dim label1 As New Label
Dim txtCreator As New TextBox
Dim combox1 As New ComboBox
Dim tabPageButton2 As New Button
tabPageButton2.Parent = tabpage
label1.Parent = tabpage
txtCreator.Parent = tabpage
combox1.Parent = tabpage
label1.Location = New Point(10, 10)
txtCreator.Location = New Point(150, 10)
combox1.Location = New Point(300, 10)
tabPageButton2.Location = New Point(20, 40)
label1.Text = "Creator"
txtCreator.Name = "txtCreator"
'fill the comboboxes...this will come from a database but testing now.
combox1.Items.Add("one")
combox1.Items.Add("two")
combox1.Items.Add("three") 'ok that works so should work from DB no problem.
tabRoleClass.TabPages.Add(tabpage)
End Sub
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
addTab("First Tab")
AddHandler Controls("tabRoleClass.tabPage1.tabPageButton2").Click, AddressOf tabPageButton_click
'AddHandler CType(Controls("tabPageButton"), Button).Click, AddressOf tabPageButton_click
'AddHandler Controls("tabPageButton").Click, AddressOf tabPageButton_click
AddHandler CType(Controls("txtCreator"), TextBox).KeyPress, AddressOf txtcreator_keypress 'the Keypress to call lookup
End Sub
Private Sub tabPageButton_click(sender As System.Object, e As System.EventArgs) 'Handles tabPageButton.click
MessageBox.Show(tabRoleClass.SelectedTab.Name.ToString)
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
addTab("Second Tab")
tabRoleClass.SelectedIndex = tabRoleClass.TabCount - 1
'AddHandler Controls("tabRoleClass.tabPage1.tabPageButton2").Click, AddressOf tabPageButton_click
'AddHandler CType(Controls("tabPageButton"), Button).Click, AddressOf tabPageButton_click
'AddHandler Controls("tabPageButton").Click, AddressOf tabPageButton_click
'AddHandler CType(Controls("txtCreator"), TextBox).KeyPress, AddressOf txtcreator_keypress 'the Keypress to call lookup
End Sub
Private Sub txtcreator_keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) 'Handles txtCreator.KeyPress
MessageBox.Show("keypress worked on " & tabRoleClass.SelectedTab.Name.ToString)
End Sub
End Class
【问题讨论】:
-
在创建控件时添加处理程序 (
addTab) -
看起来你会受益于一个继承自标签页并拥有你需要的控件和处理程序的类。使用带有名称的构造函数,您可以轻松实现串行命名。
标签: vb.net addhandler