views:

314

answers:

1

Hello,

I have an object bound to a winform and this object implements IDataErrorInfo. I have an error provider. The problem is when a property of a a property change.

There is no problem when I change the age (ie the rules are checked and displayed/removed correctly). But when I change the job title, the error is not displayed/removed (indeed the property Title do not belong to the object person). How can I perform the check ?

this.errorProvider1.DataSource = this.bindingSourcePerson;
bindingSourcePerson.DataSource = new Person();
textBoxAge.DataBindings.Add("Text", bindingSourcePerson, "Age");
textBoxJobTitle.DataBindings.Add("Text", bindingSourcePerson, "CurrentJob.Title");

public class Person : IDataErrorInfo
{
    public double Age { get; set; }
    private Job _job = new Job();
    public Job CurrentJob { get { return _job; } set { _job = value; } }

    public string this[string columnName]
    {
        get
        {
            _lastError = "";
            switch (columnName)
            {
                case "Age":
                case "CurrentJob.Title":
                    if (!string.IsNullOrEmpty(CurrentJob.Title) && Age < 16)
                        _lastError = "Invalid job.";
                    break;

                default: _lastError = "";
                    break;

            }
            return _lastError;

        }
    }

    private string _lastError = "";
    public string Error
    {
        get { return _lastError; }
    }

    public class Job
    {
        public string Title { get; set; }
    }
A: 

Hello,

if you add a property to your Person class:

public String CurrentJobTitle { get { return _job.Title; } }

and then bind the TextBoxJobTitle to CurrentJobTitle:

textBoxJobTitle.DataBindings.Add("Text", bindingSourcePerson, "CurrentJobTitle");

Or, bind the TextBoxJobTitle to bindingSourcePerson.CurrentJob like this:

textBoxJobTitle.DataBindings.Add("Text", bindingSourcePerson.CurrentJob, "Title");

will it work?

najmeddine
Pretty sure is gonna work. But don't really like it and the main object got 30-40 "submember".
Toto
if you're going to bind each -submember- to a textbox manually, you have to write at least 1 line of (hard)code for each of them. Even when using reflection you have to write somewhere a "binding" between a textbox and a property. So I think the goal is to reach exactly 1 line of code (not that the number of lines matter, but because it's hard coded, boring to modify after that). For each of your -submember- you can do: textBoxSubMember.DataBindings.Add("Text", mainObject.Submember, "SubmemberProperty");
najmeddine