res*_*ite 1 vb.net textbox winforms
我想创建一个函数或子函数,当它获得焦点时清除文本框.例如:
textbox1包含:"你的名字在这里."
当用户点击它时 在"您在这里的名字." 会消失的.我通过把它做textbox1.clear在GotFocus的事件textbox.
现在我打算在其中添加更多代码.但事情是编码会重复而且很长,因为我打算在许多文本框中执行此操作.我想最小化编码,所以我想创建一个在聚焦时清除文本框的函数,这样我就可以在GotFocus事件中调用函数并以某种方式减少编码.
我现在还不知道怎么做,所以如果有人那么我真的很感谢你给我的建议.
我正在使用visual studio 2010,并创建一个Windows窗体应用程序项目.
解决方法1
首先要知道,在VB.Net中,可以将多个事件连接到 Windows窗体中的单个事件处理程序.
Private TextBox1_GotFocus(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus, TextBox2.GotFocus
' Add event-handler code here.
End Sub
Run Code Online (Sandbox Code Playgroud)
溶液2
然后,清除文本框文本的通用事件处理程序(感谢@Miky Dinescu获取原始解决方案和C#代码)是另一种可能的解决方案,可以开始减少代码并共享一些方法.
如果要在多个表单之间共享方法,只需将此代码放在Form.vb中,或放在新类HelperClass中.
在Form.vb中:
Private Sub ClearTextBox(ByVal sender As Object, ByVal e As EventArgs)
If TypeOf sender Is TextBox Then
(DirectCast(sender, TextBox)).Text = ""
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
或者在HelperClass.vb中:
Public Shared Sub ClearTextBox(ByVal sender As Object, ByVal e As EventArgs)
If TypeOf sender Is TextBox Then
(DirectCast(sender, TextBox)).Text = ""
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
然后,您只需将此处理程序附加到所有文本框,基本上在表单的构造函数中,在FormLoad事件中或在之前调用以显示表单的"Initialize"方法中:
AddHandler textbox1.GotFocus, AddressOf Me.ClearTextBox
AddHandler textbox2.GotFocus, AddressOf Me.ClearTextBox
Run Code Online (Sandbox Code Playgroud)
要么
AddHandler textbox1.GotFocus, AddressOf HelperClass.ClearTextBox
AddHandler textbox2.GotFocus, AddressOf HelperClass.ClearTextBox
Run Code Online (Sandbox Code Playgroud)
但这意味着您需要将此处理程序附加到所有TextBox.如果您有多个处理程序,则需要将每个方法应用于每个TextBox ...
如果你想要防止内存泄漏,如果你在关闭表单时明确调用AddHandler,你也应该删除所有这些事件处理程序...
RemoveHandler textbox1.GotFocus, AddressOf HelperClass.ClearTextBox
RemoveHandler textbox2.GotFocus, AddressOf HelperClass.ClearTextBox
Run Code Online (Sandbox Code Playgroud)
所以我建议这只是为了在一些控件之间共享方法.
编辑
当然,使用循环可以在这里再次减少代码,就像@DonA建议的那样.
但别忘了RemoveHandler.
Solution3
另一种解决方案是创建自己的自定义TextBox类,该类继承自TextBox,然后在TextBox的重新处理中使用此Custom类,或者如果已经创建了项目,则替换现有的TextBox.
Public Class MyTextbox
Inherits TextBox
Protected OverridesSub OnGotFocus(ByVal e As System.EventArgs)
MyBase.OnGotFocus(e)
Me.Text = String.Empty
End Sub
End Class
Run Code Online (Sandbox Code Playgroud)
然后构建项目.您现在应该在ToolBox中看到MyTextbox.您可以使用它或用MyTextBox替换现有的TextBox
使用此方法,您只需要维护一个类的方法.而且无需担心处理程序......
面向对象编程的一个重要特性是继承:不要剥夺自己!
最后,我不确定GetFocus上的Text是一个很好的方法,你正在尝试做什么.它似乎是WinForms中的"Watermark TextBox"或"Cue Banner".所以你可能会对此感兴趣:WinForms中的Watermark TextBox或者可能考虑使用Enter Event并阻止删除用户输入.
希望这可以帮助.