I am very new to C# and have the following snippet of repeated code from one monstrosity of a program:
private void subjectBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string[] igcseSubjects = new string[5] {"IGCSE Maths", "IGCSE English", "IGCSE Chem", "IGCSE Phys", "IGCSE Bio"};
string selectedSubject = (string) subjectBox1.SelectedItem;
if (igcseSubjects.Contains(selectedSubject))
{
nBox1.Visible = aBox1.Visible = mBox1.Visible = eBox1.Visible = false;
cBox1.Visible = true;
maxBox1.Text = "100";
}
else
{
nBox1.Visible = aBox1.Visible = mBox1.Visible = eBox1.Visible = true;
cBox1.Visible = false;
maxBox1.Text = "20";
}
}
private void subjectBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string[] igcseSubjects = new string[5] { "IGCSE Maths", "IGCSE English", "IGCSE Chem", "IGCSE Phys", "IGCSE Bio" };
string selectedSubject = (string)subjectBox2.SelectedItem;
if (igcseSubjects.Contains(selectedSubject))
{
nBox2.Visible = aBox2.Visible = mBox2.Visible = eBox2.Visible = false;
cBox2.Visible = true;
maxBox2.Text = "100";
}
else
{
nBox2.Visible = aBox2.Visible = mBox2.Visible = eBox2.Visible = true;
cBox2.Visible = false;
maxBox2.Text = "20";
}
}
As you can see, the two event handlers are exact replicas, minus the controller variable names. The actual program has many more event handlers just like these, and is getting out of hand.
I am 99% sure there is a way to achieve the same outcome without all this copy/pasting, but can't figure out how to get around the different variable names -- Can I use one method?
How can I go about refactoring this code to not be so repetitive?