Search code examples
c#if-statementcombobox

What is a good substitute for an if else if in ComboBox?


I need to develop a Employee Payroll Computation for my exam.

enter image description here

I have successfully entered a code for when the Employee Number is chosen, there is a list of 1,2,3,4,5 and every number, a name appears on the Employee Name. I would like to know if there is another way to code it?

if (cmbEmployeeNum.SelectedIndex == 0)
{
    txtEmployeeName.Text = "Sheldon Cooper";                
}

else if (cmbEmployeeNum.SelectedIndex == 1)
{
    txtEmployeeName.Text = "Leonard Hofstadter";
}

else if (cmbEmployeeNum.SelectedIndex == 2)
{
    txtEmployeeName.Text = "Howard Wolowitz";
}

else if (cmbEmployeeNum.SelectedIndex == 3)
{
    txtEmployeeName.Text = "Raj Koothrappali";
}

else
{
    txtEmployeeName.Text = "Penny";
}

Also, Position Code is also in ComboBox. Do I only use the same code style because in position code, there is A, B, C and every code has an equivalent rate per day.

My teacher gave this final exam to us but he didn't really teach us the other lessons.


Solution

  • Actually, if you're going to use the event of the ComboBox called SelectedIndexChanged, you don't have to use conditional statement to show all those names on your textbox.

    You can store the names in an array and call those depends on the SelectedIndex of the combobox like below code:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string[] names = { "Sheldon Cooper", "Leonard Hofstadter", "Howard Wolowitz" };
        txtEmployeeName.Text = names[comboBox1.SelectedIndex];
    }