How to restore previous value in ComboBox when the user makes an invalid selection?

  • 2358
  • 0

摘要:How to restore previous value in ComboBox when the user makes an invalid selection?

Question:

Hi
In Windows Forms application using an unbound Combobox, the user is allowed to make a selection and change the current value displayed in the combobox. The user selection is considered valid by the application under certin conditions only, othwerwsie, the user must not change the currently displayed value.

I want to know:

1. Which event to use
2. What property to use

so that the program can do soemthing like this

Event...
If (currently selected/typed in value in the CBX is not vlaid)
{
    Messagebox.Show("You can't use this value")
    e.Cancel=True; //Should restore the value that was in the box before the user made the change
}

Reply:

you can try this code~

1. the Form1.Designer.cs

// 
// comboBox1
// 
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Items.AddRange(new object[] {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"});
this.comboBox1.Location = new System.Drawing.Point(52, 43);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(121, 20);
this.comboBox1.TabIndex = 0;
this.comboBox1.SelectionChangeCommitted += new System.EventHandler(this.comboBox1_SelectionChangeCommitted);

2. the Form1.cs

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
 ComboBox xx = (ComboBox)sender;

 if (Int32.Parse(xx.SelectedItem.ToString()) > 7)
 {
  this._previousSelectedItem = xx.SelectedItem;
 }
 else
 {
  xx.SelectedItem = this._previousSelectedItem;
 }
}

and my condition is that SelectedItem must bigger than 7,

good luck~~~

 

Quote from HERE