Click here to Skip to main content
15,891,777 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Good day to all,

here's the scenario.. i have 7 combo boxes but they all serve the same functions.. is it possible if i merged this combo boxes into 1?. i was thinking of using a public function and just call it


C#
public double Overtime()
   {
    double Salary = double.Parse(txtSalary.Text);
    double x = Salary / 26 / 8;
    double total;

    if (cbOTType1.SelectedItem.ToString() == "Regular")
       {
        total = ((x * 1.25);
       }
    else if (cbOTType1.SelectedItem.ToString() == "Rest Day OT")
       {
        total = ((x * 1.69);
       }
    else
       { total = "0.00"; }


     // Combobox 1 ~ 7 (cbOTType 1~7) would serve the same function


    return total;
    }
Posted
Updated 25-Mar-15 15:13pm
v3
Comments
Sergey Alexandrovich Kryukov 26-Mar-15 0:36am    
What is ComboBox? Do you think this is a type? Wrong. There are several types under this name. Which one?
In all case, your code is huge abuse and cannot even compile.
—SA
Sinisa Hajnal 26-Mar-15 3:03am    
Use selected value instead of selectedItem.ToString for starters. Have an enumeration of values for if elseif.

Other then that, what is preventing you from calling
Overtime (currentControl) and use passed control instead of cbOTType?

1 solution

Yes.
All event handlers have two parameters: object sender and EventArgs e
The sender parameter is the control which raised the event. so in your "combined" handler, just cast the parameter to a ComboBox:
C#
private void MyComboEvent_Handler(object sender, EventArgs e)
   {
   ComboBox db = sender as ComboBox;
   if (cb != null)
      {
      ...
      }
   }
You can then pass the Combobox instance through to your OverTime method and you get the current instance.

If however you are trying to make the same code work for seven different comboboxes, thats simple as well:
C#
public double Overtime()
    {
    double Salary = double.Parse(txtSalary.Text);
    double total = OverTime(cbOTType1, Salary);
    total += OverTime(cbOTType2, Salary);
    total += OverTime(cbOTType3, Salary);
    total += OverTime(cbOTType4, Salary);
    total += OverTime(cbOTType5, Salary);
    total += OverTime(cbOTType6, Salary);
    total += OverTime(cbOTType7, Salary);
    return total;
    }
private double OverTime(ComboBox cb, double salary)
    {
    double x = salary / 26 / 8;
    double total;

    if (cb.SelectedItem.ToString() == "Regular")
       {
        total = ((x * 1.25);
       }
    else if (cb.SelectedItem.ToString() == "Rest Day OT")
       {
        total = ((x * 1.69);
       }
    else
       { total = 0.0; }
    return total;
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900