Steven Evers
Steven Evers

Reputation: 17226

DataBinding 2 properties to 1 Control

Is it possible to databind 2 properties to 1 control? Specifically, I'm thinking phone numbers. I've got an object where all of the properties are bindable directly to 1 control, but there is an areacode and phonenumber property on the object. My users very much prefer a masked textbox for entering phone numbers as opposed to 2 separate ones.

Likewise, it's much easier to add the binding in the form load and call the persistent objects .save() method instead of populating the controls on load and re-setting them on save (that, and there's a logical disconnect between databound properties in the form code and non-bound ones).

So, I'm wondering if it's possible at all.

Edit> solved thanks to Yoooder.

The code that I wrote to solve this looks like this:

public class Person : PersistentBase
{
    private string areaCode;
    private string number;

    public string AreaCode
    {
        get { return this.areaCode; }
        set { Persist("AreaCode", this.AreaCode, value); } // pseudocode
    }

    public string Number
    {
        get { return this.number; }
        set { Persist("Number", this.number, value); }
    }

    [NonPersistent]
    public string PhoneNumber
    {
        get { return string.Format("{0}{1}", this.AreaCode, this.Number)); }
        set
        {
            PhoneParts parts = SplitIntoParts(value); // uses regex etc.
            // Validate full phone number
            this.AreaCode = parts.AreaCode;
            this.Number = parts.Number;
        }
    }
}

and I bind as I normally would

textBox1.DataBindings.Add(new Binding("Text", this.person, "PhoneNumber"));

Upvotes: 1

Views: 386

Answers (2)

STW
STW

Reputation: 46394

Data binding lets you bind 1 property from your datasource to one property on your target control; each control can have multiple bindings. So your DataSource.Value can bind to TargetControl.Text; however you cannot bind both DataSource.Value1 and DataSource.Value2 to TargetControl.Text

If I understand your use case correctly then you'd likely want your datasource to be responsible for merging the area code and phone number into a single, bindable property. This means your datasource would merge the two properties together for binding and also split them apart for saving.

Upvotes: 2

overslacked
overslacked

Reputation: 4137

As far as my experiences have been, data binding is at the property level, so a control could contain multiple bindings.

For this specific question I would suggest that two fields to store a phone number might not be the best design.

Upvotes: 0

Related Questions