Assuming you are using WinForms, you can have a single handler for
Click
event for all buttons which may look like (NOT TESTED and POORLY CODED example but I hope it's enough to give you an idea):
private void ChangeButtonColors(object sender, EventArgs e){
var button = sender as Button;
ApplyColor(button);
int id = GetIntegerId(button);
int topId = id - 5;
var top = this.Controls.Find("btn" + topId, true).FirstOrDefault() as Button;
if(top != null)
ApplyColor(top);
int bottomId = id + 5;
var bottom = this.Controls.Find("btn" + bottomId, true).FirstOrDefault() as Button;
if(bottom != null)
ApplyColor(bottom);
int leftId = id - 1;
var left = this.Controls.Find("btn" + leftId, true).FirstOrDefault() as Button;
if(left != null)
ApplyColor(left);
int rightId = id + 1;
var right = this.Controls.Find("btn" + rightId , true).FirstOrDefault() as Button;
if(right!= null)
ApplyColor(right);
}
private void ApplyColor(Button button){
if(button.BackColor == Color.Red)
button.BackColor = Color.Green;
else if(button.BackColor == Color.Green)
button.BackColor = Red;
}
private int GetIntegerId(Button button){
int id = 0;
int.TryParse(button.ID.Replace("btn",""), out id);
return id;
}