AngryHacker
AngryHacker

Reputation: 61626

How do I know when the binding is setting the textbox vs the user?

I have a form with a text box on it. I create a BindingSource object, connect my DomainObject to it, then bind the BindingSource to a TextBox. The code looks similar to this:

private BindingSource bndSource = new BindingSource();

private void Form1_Load(object sender, EventArgs e) {
    bndProposal.DataSource = new DomainObject() { ClientCode = "123", EdiCode = "456" }; 
    txtAgencyClientCode.DataBindings.Add("Text", bndProposal, "ClientCode", 
                                false, DataSourceUpdateMode.OnPropertyChanged, null);

}

private void txtAgencyClientCode_TextChanged(object sender, EventArgs e)
{
    Debug.WriteLine("txtAgencyClientCode_TextChanged");
}

public class DomainObject
{
    public string ClientCode { get; set; }
    public string EdiCode { get; set; }
}

The code works fine. However, I'd like to know the reason the TextChanged event fires: is it because it is being set by the BindingSource or is it because the user entered something (or pasted it). How do I get that information?

I've tried having a flag that's set when bindings are created, but at the time of the binding, the textbox is on a tab control that's not visible. The event actually fires when I switch to the tab with the textbox in question.

Upvotes: 1

Views: 164

Answers (2)

Jla
Jla

Reputation: 11374

You can subscribe to the event after the text is set. Disable it in the designer and add it in the form load :

private void Form1_Load(object sender, EventArgs e) {
    txtAgencyClientCode.DataBindings.Add("Text", bndProposal, "ClientCode", 
                                false, DataSourceUpdateMode.OnPropertyChanged, null);
    txtAgencyClientCode.TextChanged += new System.EventHandler(txtAgencyClientCode_TextChanged);

}

You can unsubscribe before each programmatic text modification if you want to be sure:

txtAgencyClientCode.TextChanged  -= txtAgencyClientCode_TextChanged;

Upvotes: 1

AJ.
AJ.

Reputation: 16719

Is there a reason that you have to use the TextChanged event for user entry? Could you look into using another event instead, like KeyPress? It all depends on what you need to do when the text changes. The other option would be comparing the value on TextChanged with the DataBoundItem.

Upvotes: 1

Related Questions