BlakeWebb
BlakeWebb

Reputation: 533

How do I keep a button disabled untill all the fields are filled

How would I constantly check if multiple fields have input, and once all fields have input enable the button? or is is as simple as

if( textbox1.text && textbox2.text && textbox3.text && ...){button1.isEnabled = true;}

is there an update method like in unity to check for changes?

Upvotes: 1

Views: 2780

Answers (2)

jvanrhyn
jvanrhyn

Reputation: 2824

You can link all the textboxes to the same TextChanged event and then evaluate them to see if all textboxes has been completed.

private void textBoxes_TextChanged(object sender, EventArgs e)
{
    EnableButton();
}


private void EnableButton()
{
    button1.Enabled = !Controls.OfType<TextBox>().Any(x => string.IsNullOrEmpty(x.Text));
}

Upvotes: 2

Muds
Muds

Reputation: 4116

You must use command pattern and it should then look like this --

Your command class --

 public class RelayCommand : ICommand
    {
        private Action<object> _execute;
        private Func<object, bool> _canExecute;

        public RelayCommand(Action<object> execute, Func<object,bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested += value;
                }
            }
            remove
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }
    }

Your button code --

<Button Content="Click Me" Command="{Binding ButtonCommand}"/>

Your command property --

public ICommand EnabledCommand { get; set; }

In your constructor --

ButtonCommand = new RelayCommand(ButtonCommandHandler, CanClick);

Your command handler --

private void ButtonCommandHandler(object obj)
    {
        // Do what ever you wanna
    }

Your can execute handler --

 private bool CanClick(object arg)
    {
        return textbox1.Text.Trim().Length > 0 && textbox2.Text.Trim().Length > 0;
    }

Upvotes: 1

Related Questions