0

Possible Duplicate:
Text box validation not working

Right now I have 5 text boxes that when any one of the fields are left blank it turns the box yellow and outputs the statement in my label called "lblError" the following error ""Please enter valid data!" This is listed in my catch statement. I would like for the lblError to output the text statements I have listed for each text box. So if the first name and last name were blank the lblError would output both messages. I am new to C# so it is a little confusing to me.

public partial class frmPersonnel : System.Web.UI.Page
{
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            DateTime dt1;
            DateTime dt2;

            if (txtFirstName.Text == "")
            {
                txtFirstName.BackColor = System.Drawing.Color.Yellow;
                lblError.Text = "Please enter first name";
            }
            if (txtLastName.Text == "")
            {
                txtLastName.BackColor = System.Drawing.Color.Yellow;
                lblError.Text = "Please enter last name!";
            }
            if (txtPayRate.Text == "")
            {
                txtPayRate.BackColor = System.Drawing.Color.Yellow;
                lblError.Text = "Please enter pay rate!";
            }
            if (txtStartDate.Text == "")
            {
                txtStartDate.BackColor = System.Drawing.Color.Yellow;
                lblError.Text = "Please enter start date!";
            }
            if (txtEndDate.Text == "")
            {
                txtEndDate.BackColor = System.Drawing.Color.Yellow;
                lblError.Text = "Please enter end date!";
            }
            dt1 = DateTime.Parse(txtStartDate.Text);
            dt2 = DateTime.Parse(txtEndDate.Text);


            if (DateTime.Compare(dt1, dt2) > 0)
            {
                txtStartDate.BackColor = System.Drawing.Color.Yellow;
                txtEndDate.BackColor = System.Drawing.Color.Yellow;
                lblError.Text = "Start Date must not be greater than End Date.";
            }

            else
            {
                Session["txtFirstName"] = txtFirstName.Text;
                Session["txtLastName"] = txtLastName.Text;
                Session["txtPayRate"] = txtPayRate.Text;
                Session["txtStartDate"] = txtStartDate.Text;
                Session["txtEndDate"] = txtEndDate.Text;
                Server.Transfer("frmPersonalVerified.aspx");
            }
        }
        catch (Exception)
        {
            lblError.Text = "Please enter valid data!";
        }
    }
}
1
  • 1
    This is why there are Validation events.
    – LarsTech
    Nov 10, 2011 at 13:50

6 Answers 6

2

You will need to concatenate the error messages - if an error was found, concatenate and add a new line, if not, just use the new error message:

if(string.IsNullOrWhiteSpace(lblError.Text))
{
   lblError.Text = "Please enter last name!";
}
else
{
   lblError.Text += "Please enter last name!" + Environment.NewLine;
}

The above is just an example for one of the checks.

I suggest extracting the common logic to a method of its own and reusing it (just pass as parameters the error message and the control to check, for example).

6
  • Thanks, how does the example you have tie back to the text box for the last name? I mean how does the line of code know that the last name text box is blank or not? Thanks for your time.
    – Mike
    Nov 10, 2011 at 14:21
  • I am testing for it in the if with: string.IsNullOrWhiteSpace.
    – Oded
    Nov 10, 2011 at 14:21
  • So I would use the same code copied over for each text box?
    – Mike
    Nov 10, 2011 at 14:23
  • @Mike - you could. Or you could extract the common code to a method, as I suggest at the end of my answer.
    – Oded
    Nov 10, 2011 at 14:27
  • Sorry, I'm trying to do some research on this and I don't understand it. I am new to coding and this is a little difficult for me. I'm not sure how to set it up by extracting the common code to a method.
    – Mike
    Nov 10, 2011 at 14:37
1

You could do this.

Add += eg lblError.Text += "Please enter first name "; This will append to the text already in the textbox.

public partial class frmPersonnel : System.Web.UI.Page
{
  protected void btnSubmit_Click(object sender, EventArgs e)
  {
    try
    {
        DateTime dt1;
        DateTime dt2;

        // Add this 
        lblError.Text = "";

        if (txtFirstName.Text == "")
        {
            txtFirstName.BackColor = System.Drawing.Color.Yellow;
            lblError.Text += "Please enter first name ";
        }
        if (txtLastName.Text == "")
        {
            txtLastName.BackColor = System.Drawing.Color.Yellow;
            lblError.Text += "Please enter last name! ";
        }
        if (txtPayRate.Text == "")
        {
            txtPayRate.BackColor = System.Drawing.Color.Yellow;
            lblError.Text += "Please enter pay rate! ";
        }
        if (txtStartDate.Text == "")
        {
            txtStartDate.BackColor = System.Drawing.Color.Yellow;
            lblError.Text += "Please enter start date! ";
        }
        if (txtEndDate.Text == "")
        {
            txtEndDate.BackColor = System.Drawing.Color.Yellow;
            lblError.Text += "Please enter end date! ";
        }
        dt1 = DateTime.Parse(txtStartDate.Text);
        dt2 = DateTime.Parse(txtEndDate.Text);


        if (DateTime.Compare(dt1, dt2) > 0)
        {
            txtStartDate.BackColor = System.Drawing.Color.Yellow;
            txtEndDate.BackColor = System.Drawing.Color.Yellow;
            lblError.Text += "Start Date must not be greater than End Date. ";
        }

        else
        {
            Session["txtFirstName"] = txtFirstName.Text;
            Session["txtLastName"] = txtLastName.Text;
            Session["txtPayRate"] = txtPayRate.Text;
            Session["txtStartDate"] = txtStartDate.Text;
            Session["txtEndDate"] = txtEndDate.Text;
            Server.Transfer("frmPersonalVerified.aspx");
        }
    }
    catch (Exception)
    {
        lblError.Text = "Please enter valid data!";
    }
  }
}

Really though, I would suggest that you look at using Validation controls. They are quite easy to add to your form. And would help you out in this case

0

You could -

  • Store the error message for each invalid field in a StringBuilder
  • If the StringBuilder contained any content at the end of the process output your collected error messages to the lblError control
0

When checking for empty string, it's better to use String.IsNullOrEmpty.

Labels, assuming it's a single line label, can only display one thing. Whenever you assign the Text property, whatever text was stored before is overwritten. If you have to display multiple things, you should use a control that displays more text and append it. You're only going to hit your catch block if an exception is thrown in the try block.

0

One idea would be to declare an IDisposable class to collect all validation errors.
This class is responsible to collect error messages and throw them (if any) when the context is disposed. (i.e. when using has reached the closing bracket)

try
{
    using (var cx = new ValidationContext())
    {
        if (this) cx.AddError("Please provide a value for ...");
        if (that) cx.AddError("Please provide a value for ...");
    }
}
catch (Exception ex)
{
    lblError.Text = ex.Message;
}

and define ValidationContext as below:

public class ValidationContext : IDisposable
{
    StringBuilder Builder { get; set; }

    public ValidationContext()
    {
        Builder = new StringBuilder();
    }

    public void AddError(string message) { Builder.AppendLine(message); }

    public void Dispose()
    {
        var total = Builder.ToString().Trim();
        if (total.Length > 0)
        {
            throw new Exception(total);
        }
    }
}

This is the simplest implementation of this concept, You can add more features to it to support adding error to the ValidationContext.Current from any where in you code (even nested methods)).
If you do this you would be able to add only one using{} to your UI and call ValidationContext.Current.AddError() from all parts of your application/library.

0

The main problem is that your method is throwing an exception which is why you are only getting the message as defined in the catch block. I would suspect that the error is being thrown by this code:

dt1 = DateTime.Parse(txtStartDate.Text);
dt2 = DateTime.Parse(txtEndDate.Text);

DateTime.Parse() will throw an exception if the text string passed in as the parameter doesn't parse exactly as DateTime value.
A fix for this could be to use the DateTime.TryParse() method instead which will not throw an exception:

DateTime dt1 = DateTime.MinValue;
DateTime dt2 = DateTime.MinValue;

if (DateTime.TryParse(txtStartDate.Text, out dt1) &&
    DateTime.TryParse(txtEndDate.Text, out dt2))
{
    if (DateTime.Compare(dt1, dt2) > 0) 
    {
     ....
    }
    else
    {
     ....
    }
}
else
{
     // set error stating date time values are not in a parsable format
}

The second issue you have is you are overwriting your error label each time with the following code:

lblError.Text = "Please enter first name";

One way of avoiding this is to use:

lblError.Text += "Please enter first name<br />";

Alternatively you could use a StringBuilder to append messages as they are required and then apply this to the error label at the end of the message.

Not the answer you're looking for? Browse other questions tagged or ask your own question.