AngryHacker
AngryHacker

Reputation: 61606

Two way binding with UI quirks

I haven't really done a two way binding project before, so this might be a simple question.

I have an business object with all the right interfaces (INotifyPropertyChanged, etc...). I bound a Int32 property called CPP to a textbox named txtCPP via a BindingSource. The rules state that if CPP is less than 0, the text box should be blank, otherwise should display a value.

So to make that happen, I changed the property from Int32 to Int32? (nullable) and when the backing variable of the CPP property is less than zero, I actually return null.

This actually works fine with the UI. The problem comes when I want to persist the business object to the database. An external method takes the business object, reads its properties (including CPP) and persists them to the database. And obviously, instead of CPP being -1, it is being written as null.

I am sure I am not the first person to come up with this issue when doing two-way binding projects. How does one typically handle these problems in a clean way without polluting the form code with edge cases like that?

Upvotes: 2

Views: 179

Answers (1)

JMarsch
JMarsch

Reputation: 21753

It sounds as though your rule about the box being blank is a UI rule, and not a data rule (so the data value really is -1, it just should be displayed as blank).

If that's the case, lets move the blank logic into the UI. So, your data object property returns an int (and it returns the real value of the int), and then you can morph it in your display.

One way to do that would be with formatting -- you can specify a Formatter with your databinding, or you can hook the Format event on the databinding.

Of course, you still need to decide what to do when the user enters a blank value into the textbox...

Here's a really simple-minded example, using the Format event in the databinding:


var binding = this.textBox1.DataBindings.Add("Text", MyObject, "AValue", true);
binding.Format += (s, args) =>
    {
        int i = (int)args.Value;
        if (i <= 0)
        args.Value = "";
    };

Upvotes: 3

Related Questions