开发者

Disable button till txtBox is valid C#

I'm looking to disable a "submit" button till 2 text boxes have a 开发者_运维技巧value in them. I'm not totally sure how to go about this.


As this is WinForms, you should monitor the TextChanged event on your textboxes and call a method that updates the enabled state of your button (string.IsNullOrEmpty and string.IsNullOrWhiteSpace are helpful here).

The following example shows a simple situation where you want content in the text boxes before the button is enabled.

private void OnTextChanged(object sender, EventArgs args)
{
    UpdateUserInterface();
}

private void UpdateUserInterface()
{
    this.myButton.Enabled = !string.IsNullOrWhiteSpace(this.textBox1.Text) &&
                            !string.IsNullOrWhiteSpace(this.textBox2.Text);
}

If you want to do something more complex and time-consuming to determine the enabled state, you may want to consider something that delays the button state update until typing is done. For example, a timer with small interval that is re-started each time the TextChanged event is fired and stopped in its own Tick event handler where you finally call the UpdateUserInterface method.

Side notes
Since learning this is a WinForms application, I have relegated the following points to side-notes for those hunting this information.

For WPF, you could use a similar approach or use some cunning bindings with appropriate value converters. I'd recommend keeping it simple though.

For ASP.NET, this can be done client side with javascript - attaching to the onChange events of the text boxes and testing both for values*.

**Thanks to Oded for that extra info.*


In Winfoems or WPF, hook into the TextChanged events of both TextBoxes with a single handler. In that handler, look at the current Text of both TextBoxes (don't go in too deep though, as the event is fired on every keystroke so in-depth validation will slow down the UI response), and if the texts are not empty or only whitespace, enable the button; otherwise, disable it.

In ASP.NET, you'll need to use JavaScript. There's a similar OnChanged event for textboxes in the DOM, to which you can assign a Javascript function that will perform a similar job as in WinForms. Be careful, as browsers can be run with JavaScript disabled, so you still need to check for null on the server side and make sure the button isn't disabled by default (only by JavaScript, either with the OnChanged function or something that runs on document load).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜