Results 1 to 2 of 2

Thread: [2.0] Validating Text boxes

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Apr 2006
    Posts
    18

    Question [2.0] Validating Text boxes

    I am working on a Windows application in C#

    I have two text boxes, to be validated with (txtFirstName and txtLastName)

    Please could someone give me the syntax to use txtFirstName_Validating()
    TO achieve the validation.
    I have put the validation code inside the Button click event.

    Please could you give me the best approach to validate the text boxes.

    Thank you,
    -----------------------------------------------------------------------

    private void txtFirstName_Validating(object sender, CancelEventArgs e)
    {
    if (string.IsNullOrEmpty(txtFirstName.Text))
    {
    MessageBox.Show("First Name required!");
    }

    }

    private void btnLookUp_Click(object sender, EventArgs e)
    {
    if ((txtFirstName.Text == string.Empty) || (txtLastName.Text ==
    string.Empty))
    {
    MessageBox.Show("Please enter the Name..");
    }

    }

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: [2.0] Validating Text boxes

    There's no point using IsNullOrEmpty because the Text property of a control can NEVER return a null reference. You only have to check for an empty string. You would use something like this in the Validating event handler:
    Code:
    if (this.txtFirstName.Text == string.Empty)
    {
        e.Cancel = true; //This line prevents the control losing focus.
        MessageBox.Show("Please enter a value for First Name.");
    }
    Note that this does not stop the user entering whitespace only. I would also recommend using code like this in the Leave event:
    Code:
    //Remove leading and trailing whitespace.
    this.txtFirstName.Text = this.txtFirstName.Text.Trim();
    The Leave event is raised before the Validating event so this will turn a whitespace only value into an empty string before validating.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width