3

I'm trying to create a method that will custom validate any TextBox control passed to it.

Here's what I've got so far:

A Custom Validator

protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args)
    {
        CustomValidator ThisValidator = sender as CustomValidator;
        TextBox MyBox = FindControl(ThisValidator.ControlToValidate) as TextBox;

        args.IsValid = isValid(MyBox);
    }

Validation Method

protected bool isValid(System.Web.UI.WebControls.TextBox MyBox)
    {
        bool is_valid = MyBox.Text != "";
        MyBox.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
        return is_valid;
    }

The code compiles OK but I get a

NullReferenceException was unhandled by user code

on

bool is_valid = MyBox.Text != "";

When I run the validation.

I know I'm close (well I think I am) but where am I going wrong?

ComfortablyNumb
  • 1,448
  • 10
  • 37
  • 64

4 Answers4

1

you first need to check that the object itself exist, after casting:

bool is_valid = MyBox != null;

and after that you can check its text property

Shlomi Komemi
  • 5,445
  • 3
  • 28
  • 41
1

Your problem is the FindControl() method is not recursive, therefore MyBox is null. You'll have to write a recursive FindControl() method like the one here if you want it to work correctly.

You'll probably also want to check if MyBox is null and return out of the method if it is.

EJC
  • 2,062
  • 5
  • 21
  • 33
0

For completeness this code did the trick for me:

protected void CustomValidatorDelLN_ServerValidate(object sender, ServerValidateEventArgs args)
    {
        args.IsValid = isValid(txtDeliveryLastName);
    }

    protected bool isValid(System.Web.UI.WebControls.TextBox MyBox)
    {
        bool is_valid = MyBox.Text != "";
        MyBox.BackColor = is_valid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
        return is_valid;
    }
ComfortablyNumb
  • 1,448
  • 10
  • 37
  • 64
-4

You are trying to validate an empty text box. You can't validate an empty string.

Botonomous
  • 1,746
  • 1
  • 16
  • 39
  • 2
    An empty string will not cause a `NullReferenceException`. – Anthony Pegram Sep 23 '11 at 14:47
  • bool is_valid = MyBox.Text != ""; This will not cause NullReferenceException ? Why not do bool is_valid = MyBox.Text != "null" like the above poster – Botonomous Sep 23 '11 at 14:49
  • The problem isn't the empty string. It's accessing the `.Text` property of a null object. Look at it another way. Is an empty string a null reference? (No.) Or could the textbox variable contain a null reference? (Yes.) Then ask if you can access a property of a null reference. – Anthony Pegram Sep 23 '11 at 14:52
  • I guess i said it wrong...I meant the null object, not a null string. Yes a string can be empty and not null. Thanks for the correction. – Botonomous Sep 23 '11 at 14:58