Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

winforms - Validating Method is not Called on button click C#

I am new to programming and have little programming experience, build a WinForm application that has 5 text boxes, write a method ValidateTextBoxForAlphabet() for validating text only on the first 3 textboxes and I write another method for checking the numbers only, I called ValidateTextBoxForAlphabet on button click and that is successfully called but ValidateBatch() method does not call on button click.

On Button Click:

 private void button1_Click(object sender, EventArgs e)
    {

        ValidateTextBoxForAlphabet(textBox1);
        ValidateTextBoxForAlphabet(textBox2);
        ValidateTextBoxForAlphabet(textBox3);
        textBox4.Text = string.Concat(textBox4.Text.Where(char.IsLetterOrDigit));
        ValidateBatch(textBox5);

    }

These are my both methods:

 public void ValidateTextBoxForAlphabet(TextBox tb)
        {
            if(!System.Text.RegularExpressions.Regex.IsMatch(tb.Text, "^[a-zA-Z ]"))
            {
                MessageBox.Show("Full Name, Father Name and University name can't accept numbers..." , "Warning", MessageBoxButtons.OK , MessageBoxIcon.Warning);
            }
        }

 public void ValidateBatch(TextBox tx)
    {
        if (!System.Text.RegularExpressions.Regex.IsMatch(tx.Text, "[^0-9]"))
        {
            MessageBox.Show("Batch contain only NUMBERS..", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //textBox5.Text = textBox5.Text.Remove(textBox5.Text.Length - 1);
        }
    }
question from:https://stackoverflow.com/questions/65917088/validating-method-is-not-called-on-button-click-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

just as @JonasH you validation will result to problems and bad experience to the user and hard to know where the error is coming from try validation on textBox1_TextChanged event this way use knows what is being entered is not allowed.

   private void textBox1_TextChanged(object sender, EventArgs e)
    {
         ValidateTextBoxForAlphabet(textBox1);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...