开发者

Pass a Control to a Method

开发者 https://www.devze.com 2023-04-07 05:03 出处:网络
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:

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

开发者_Python百科
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?


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.


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


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;
    }


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号