hellow
hellow

Reputation: 13440

Validation Event for Combobox when text is updated

I have a comboxbox (okay, in real a have a ToolStripComboBox) where I want a cancleable event that is triggered under certain conditions:

so a "normal" validation event, but when I do the following

this.speedSelector.Validating 
+= new System.ComponentModel.CancelEventHandler(this.speedSelector_Validating);

This event is only triggered, when I try to close the application via [X]. Also I can't leave the application when a not valid text is present, that works, but how to trigger that event on my conditions above?

Regards,

Upvotes: 0

Views: 4384

Answers (2)

user153923
user153923

Reputation:

You will probably need to store the initial value somewhere (like maybe in the Control's universal Tag field).

You could validate the control on any of the events: SelectedIndexChanged, SelectionChanged, TextUpdate, etc.

The value stored in the control should not change when the control gains or loses focus.

public Form1() {
  InitializeComponent();
  speedSelector.Tag = speedSelector.Text;
  speedSelector.SelectedIndexChanged += new System.EventHandler(this.speedSelector_Changed);
  speedSelector.SelectionChangeCommitted += new System.EventHandler(this.speedSelector_Changed);    
  speedSelector.TextUpdate += new System.EventHandler(this.speedSelector_Changed);
}

private void speedSelector_Changed(object sender, EventArgs e) {
  if (validData(speedSelector.Text)) {
    speedSelector.Tag = speedSelector.Text;
  } else {
    speedSelector.Text = speedSelector.Tag.ToString();
  }
}

private static bool validData(string value) {
  bool result = false;
    // do your test here
  return result;
}

Upvotes: 1

Richthofen
Richthofen

Reputation: 2086

Validating will be called when moving focus from a control on the dialog that has the CausesValidation property set to true to another control that has the CausesValidation property set to true, e.g. from a TextBox control to the OK button. Maybe your validation happens when you close the window because you have CausesValidation set on the window, and not on the appropriate controls?

You could also just move all the validation into an OnBlur event for your control and do it that way.

Upvotes: 0

Related Questions