views:

165

answers:

3

I have an Address object defined simply as follows:

public class Address
{
    public string StreetNumber { get; set; }
    public string StreetAddress { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
}

Fairly simple. On the advice an answer to another question I asked, I am referring to this blog post when databinding my UI to an object of type Person (which contains an Address MailingAddress field).

The problem is that the IDataError interface method isn't validating any of the properties of the Address type.

public string this[string columnName]
{
    get
    {
        string result = null;

        // the following works fine
        if(columnName == "FirstName")
        {
            if (string.IsNullOrEmpty(this.FirstName))
                result = "First name cannot be blank.";
        }
        // the following does not run 
        // mostly because I don't know what the columnName should be
        else if (columnName == "NotSureWhatToPutHere")
        {
            if (!Util.IsValidPostalCode(this.MailingAddress.PostalCode))
                result = "Postal code is not in a know format.";
        }
        return result;
    }
}

So, obviously I don't know what the columnName will be... I've stepped through it and it has never been anything other than any of the public properties (of intrinsic types). I've even tried running and breaking on a statement like:

if (columnName.Contains("Mailing") || columnName.Contains("Postal"))
    System.Windows.Forms.MessageBox.Show(columnName);

All to no avail.

Is there something I'm missing?

+2  A: 

You need to define IErrorInfo on all the classes that you want to supply error messages for.

Brian
A: 

to Brian. I think You're not quite right. Sometimes object has different behaviour and restrictions depending on context of parent object. So, imagine if we have object Sum with properties Amount and Currency. Now we have class Remittance with amount and currency. So, suppose we have several types of remittances and in some type amount is limited by its nature. So how the field of type Sum would know that its amount should in some case be limited and in other - not?

Andrey Khataev
A: 

Take a look at my answer here.

This explains how to use a modelbinder to add 'class-level' checking of your model without having to use IDataError - which as you have seen here can be quite clumsy. It still lets you use [Required] attributes or any other custom validation attributes you have, but lets you add or remove individual model errors. For more on how to use data annotations I highly recommend this post from Scott Gu.

Simon_Weaver