Search code examples
c#asp.netcustomvalidator

Can't convert 'data annotations' to 'bool'


From the http://msdn.microsoft.com/en-us/library/f5db6z8k(v=vs.100).aspx

i've created a customeValidators.cs page, which checks if data entered exists in Db. This works. However when i try to call this from the necessary pagewith

protected void runUniqueReference(object source, ServerValidateEventArgs args)
{
    args.IsValid = (CustomValidators.UniqueReference(BOQRefTextBox.Text));
}

i get the error with CustomValidators.UniqueReference, can't convert 'data annotations' to 'bool' any idea? EDIT;

 public static ValidationResult UniqueReference(string Reference)
    {
        ContextDB db = new  ContextDB();

        var lisStoredInDB =
            (from Bill in db.Bill_Of_Quantities
             where Bill.Reference == Reference
             select Bill.Reference).ToList();

        if (lisStoredInDB.Count != 0)
        {
            return new ValidationResult(string.Format("This reference is already stored in the database, Please enter another"));
        }

        return ValidationResult.Success;
    }

Solution

  • args.IsValid is of type bool, and CustomValidators.UniqueReference mustn't return a value of that type. Therefore,

    args.IsValid = (CustomValidators.UniqueReference(BOQRefTextBox.Text));
    

    won't work since you can't assign whatever the return value of UniqueReference is to IsValid.

    Since UniqueReference returns an ValidationResult, it should probably look like this:

    args.IsValid = (CustomValidators.UniqueReference(BOQRefTextBox.Text)).IsValid;