如何启用按钮上,但我的文本字符串? [英] How do I enable button while there is a string in my textbox?

查看:88
本文介绍了如何启用按钮上,但我的文本字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,并在窗体2按钮。当一个项目被点击在Form1,Form2的出现。我想保持禁用,而文本框是空的,但是当用户开始打字,我想使按钮窗体2按钮。

I have a textbox and a button in form2. When an item is clicked in form1, form2 appears. I would like to keep the button in form2 disabled while the textbox is empty, but when user starts typing, I'd like to enable the button.

我已经尝试使用如果一个在initialisecomponent(经过我的构造函数)像这样,但它不工作:

I have tried using an if in my constructor after the initialisecomponent() like so, but it does not work:

if(textbox1.text != "")
{
   btnOne.Enabled = true;
}



我也试图调用一个名为 checkText法( )它使用一个do-while循环的INITIALISE组件后检查,如:

I have also tried calling a method called checkText() after the initialise component which uses a do-while loop to check like:

do{
    btnOne.Enabled = true
  }
 while(textbox1.text != "");



谁能帮助?

Can anyone help?

推荐答案

您需要使用一个事件。检查出的的框TextChanged 事件文本框控制

You need to use an event. Check out the TextChanged event for the TextBox control.

基本上,你就会想是这样的:

Basically you will want something like this:

private void textbox1_TextChanged(object sender, EventArgs e)
{
    btnOne.Enabled = !string.IsNullOrEmpty(textbox1.Text);
}

如果您使用的是Visual Studio中,您可以执行以下操作来添加事件代码

If you are using Visual Studio you can do the following to add the event code.


  • 开启设计视图

  • 选择TextBox控件

  • 查看活动窗口

  • 找到了框TextChanged事件

  • 双击值空间,代码会自动添加这个方法:让您以

  • Open designer view
  • Select the TextBox control
  • View the "Events" window
  • Find the "TextChanged" event
  • Double-click the value space, and the code will be added automatically for you to work with

注意工作将要求用户在文本框失去焦点事件触发之前控制。如果你想那么作为你型解决方案,签出的的KeyUp 事件而不是

Note: This approach will require the user to "lose focus" on the TextBox control before the event fires. If you want an as-you-type solution then check out the KeyUp event instead

@Asif已就为空白字符检查过好点。这是你对什么是有效的电话,但如果你不希望允许空白值被使用,那么你可以使用的 IsNullOrWhiteSpace 方法来代替 - 但是,这需要您使用.NET Framework 4.0或更高版本

@Asif has made a good point regarding checking for whitespace characters too. This is your call on what is valid, but if you do not want to allow whitespace value to be used then you can use the IsNullOrWhiteSpace method instead - however, this requires you to be using .Net Framework 4.0 or higher

这篇关于如何启用按钮上,但我的文本字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆