vb.net 如何在文本框更改时启用/禁用按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17391684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Enable/Disable button upon text-box changes
提问by Milkncookiez
I have a text-box(es) which contain directory. So I check whether this directory exists on the current machine and if it doesn't - I want the button to get Disabled.
我有一个包含目录的文本框。所以我检查当前机器上是否存在这个目录,如果不存在 - 我希望按钮被禁用。
Also if the text-box is empty, I want the button to get Enabled.
此外,如果文本框为空,我希望按钮启用。
Long story, short - I want to control the availability of the button upon changes in the text-box. I know how to check for these changes and I also know that this is done using EvenHandlers and Listeners, but I don't really know how to work with them, and if somebody could give me a sample code or step-explanation of how to make it - it would be great. Cuz I need it fast.
长话短说 - 我想在文本框中更改时控制按钮的可用性。我知道如何检查这些更改,我也知道这是使用 EvenHandlers 和 Listeners 完成的,但我真的不知道如何使用它们,如果有人可以给我一个示例代码或步骤说明如何让它 - 会很棒。因为我需要它快。
EDIT:The thing is that I want it all to be dynamic, so I suppose I need a Listenerwhich will keep track of the condition of the text-boxes values.
编辑:问题是我希望这一切都是动态的,所以我想我需要一个Listener来跟踪文本框值的条件。
F.e., the text-box is empty, and the button is Enabled. Then I start typing a directory, and because the typed path is not a valid directory - the button is Disabled. But the moment this directory gets valid - the button gets Enabled.
Fe,文本框为空,按钮已启用。然后我开始输入一个目录,因为输入的路径不是一个有效的目录 - 按钮被禁用。但是当这个目录有效时 - 按钮被启用。
回答by varocarbas
Add a button (Button1) and a textbox (TextBox1) to your form and this code:
将按钮 ( Button1) 和文本框 ( TextBox1) 添加到您的表单和以下代码:
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
If (TextBox1.Text Is Nothing Or TextBox1.Text.Trim().Length < 1) Then
Button1.Enabled = False
ElseIf (Not System.IO.Directory.Exists(TextBox1.Text)) Then
Button1.Enabled = False
ElseIf (System.IO.Directory.Exists(TextBox1.Text)) Then
Button1.Enabled = True
End If
End Sub
回答by Steve
You want the Button disabled if the directory doesn't exist and enabled if exists then
如果目录不存在,您希望按钮禁用,如果存在则启用
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
Button1.Enabled = Directory.Exists(TextBox1.Text)
End Sub
(Requires the Imports System.IO)
(需要Imports System.IO)
回答by matzone
Try this ...
尝试这个 ...
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
Dim sDir as String=TextBox1.Text
If sDir.Length = 0 Then
Button1.Enabled = True
Else
Button1.Enabled = System.IO.Directory.Exists(sDir)
End If
End Sub

