0

I am doing my project in VS2012 Windows Forms using C#.

My probem is I am validating a textbox when the control loses focus; check it is empty or not. My textbox name is ChildFirstName and my code is:

private void ChildFirstName_Leave(object sender,EventArgs e)
{
    if (ChildFirstName.Text == String.Empty)
    {
        ChildFirstName.Focus();
        ChildFirstName.ForeColor = Color.Red;
    }
}

But this is not working can anybody say what is the actual problem?

3
  • What is you goal exactly? I suppose you want the BackColor of the textbox to turn red, right? Not ForeColor Commented Nov 25, 2013 at 7:55
  • possible duplicate of C# Validating input for textbox on winforms Commented Nov 25, 2013 at 7:56
  • Code is entering IF statement? Commented Nov 25, 2013 at 7:58

1 Answer 1

1

There is a flaw in the code you have written. ForeColor property is used to define text color and not background color. So in your code you make a check if the there is no text then the change the color of the text to red. It does not make much sense to me.

If you wish to change the background color of the textbox then use BackColor property.

    private void ValidateTextBox(object sender)
    {
        TextBox textBox = (sender as TextBox);
        if (textBox == null)
            return;

        if (string.IsNullOrEmpty(textBox.Text))
        {
            textBox.Focus();
            textBox.BackColor = Color.Red;
        }
    }

Call above method in your leave event of textboxes.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.