Simplest Method to monitor changes between combo box values

533 views Asked by At

I'm looking for an elegant way to track changes between values for a combo box. What I'm looking to do is fire a custom event when the SelectionChanged event happens, but only for a specific value changes. This implies knowing what the initial value was. The event will only be fired when the initial value is changed from z. If the initial value is a, b, or c, the event will not be fired. But if the initial value was z, it will be fired.

Does anyone have an elegant way to solve this problem?

1

There are 1 answers

0
Amar Palsapure On BEST ANSWER

For this you will have to create a custom event handler and may be custom event args,

 //Event Handler Class
 public class SpecialIndexMonitor
 {
      public event EventHandler<SpecialIndexEventArgs> SpecialIndexSelected;
      //Custom Function to handle Special Index
      public void ProcessRequest(object sender, System.EventArgs e)
      {
           //Your custom logic
           //Your code goes here
           //Raise event
           if(SpecialIndexSelected != null)
           {
               SpecialIndexEventArgs args = new SpecialIndexEventArgs{
                    SelectedIndex = ((ComboBox) sender).SelectedIndex;
               };
               SpecialIndexSelected(this, args);
           }
      }
 }

 //Custom Event Args
 public class SpecialIndexEventArgs : EventArgs
 {
     //Custom Properties
     public int SelectedIndex { get; set; } //For Example
     //Default Constructor
     public SpecialIndexEventArgs ()
     {
     }
 }

Inside your form

 //Hold previous value
 private string _previousItem;

 //IMPORTANT:
 //After binding items to combo box you will need to assign, 
 //default selected item to '_previousItem', 
 //which will make sure SelectedIndexChanged works all the time

 // Usage of Custom Event
 private void comboBox1_SelectedIndexChanged(object sender, 
    System.EventArgs e)
 {
      string selectedItem = (string)comboBox1.SelectedItem;
      if(string.Equals(_previousItem, )
      switch(_previousItem)
      {
          case  "z":
          {
              SpecialIndexMonitor spIndMonitor = new SpecialIndexMonitor();
              spIndMonitor.SpecialIndexSelected += 
                   new EventHandler<SpecialIndexEventArgs>(SpecialIndexSelected);
              break;
          } 
          case "a":
          case "b":
              break;   
      }
      _previousItem = selectedItem; //Re-Assign the current item
 }
 void SpecialIndexSelected(object sender, SpecialIndexEventArgs args)
 {
     // Your code goes here to handle the special index
 }

Haven't compiled the code, but logically it should work for you.