Mallory Rich Mallory Rich - 2 months ago 6
C# Question

Clear All TextBoxes when Input is changed in a certain box in WinForm program

I have an application where the user enters their name and weight and it will convert the weight. I was wondering if there was a way that if the user's name input was less than 2 characters the 'calculate' button would be disabled and would re-enable when more than 2 characters. I am required to create an isValid method and when I run it my application does not disable the button.

public bool isValid (String text)
{
if (string.IsNullOrWhiteSpace(Name.Text) || Name.Text.Length < 2)
{
return false;
}
else
{
return true;
}
}
private void ValidateName()
{

while (isValid(Name.Text) == false)
{
this.ConvertBtn.Enabled = false;
}

}

Answer

Use TextChanged Event

private TextBox_TextChanged(object sender, EventArgs e)
{
    TextBox myTextBox = (TextBox)sender;
    this.ValidateName(myTextBox.text);
}

In this case IsValid method will be executed when any changes happened in the TextBox.

I think in your case Leave Event will be better since it will execute only when user leave a control

private void TextBox_Leave(object sender, EventArgs e)
{
    TextBox myTextBox = (TextBox)sender;
    this.ValidateName(myTextBox.text);
}

And change your IsValid method to use parameter passed there

public bool isValid (String text)
{
    cosnt int MIN_LENGTH = 2;
    if (string.IsNullOrWhiteSpace(text) == true) return false;
    if (text.Length < MIN_LENGTH) return false;

    return true;
}

Then you don't need a loop in the Validate method

private void ValidateName(string name)
{
    this.ConvertBtn.Enabled = this.IsValid(name);
}