Search code examples
c#buttoncase

I want to eliminate all of these case statements (too messy)


I am writing a test program which returns a string "P3-PASS" or "P3-FAIL. In all there are 12 possible tests, P3 to P14 ("P3-FAIL" to "P14-PASS").

I have a button "All_Tests" which calls each test 1 by 1, and the associated button changes colour based on the result.

Ideally I want to do something like PageNum.Background = Brushes.Red, but I can't do this because I can't use a string to access the button. Hence the case statements below. Is there a way to simplify this, because it looks awful. OR is there a way to access the relevant button using a string, or similar. Many Thanks

int PageNum = Int32.Parse(PageTstName);

switch (PageNum)
{
    case 3:
        if (TstResult == "PASS")
        {
            Pg3.Background = Brushes.SeaGreen;
            Pg3.Foreground = Brushes.White;
        }
        else // TstResult is "FAIL"
        {
            Pg3.Background = Brushes.Red;
            Pg3.Foreground = Brushes.White;
        }
        break;

    case 4:
        if (TstResult == "PASS")
        {
            Pg4.Background = Brushes.SeaGreen;
            Pg4.Foreground = Brushes.White;
        }
        else // TstResult is "FAIL"
        {
            Pg4.Background = Brushes.Red;
            Pg4.Foreground = Brushes.White;
        }
        break;

    case 5: .....etc

Solution

  • You can create a dictionary that maps the numbers to the controls, e.g.

    var controlsByPageNum = new Dictionary<int, Button>() 
    {
      { 3, Pg3 },
      { 4, Pg4 },
      { 5, Pg5 },
      // ...
    }
    

    When receiving the test results, you can get the control like this:

    int PageNum = Int32.Parse(PageTstName);
    var btn = controlsByPageNum[PageNum];
    if (TstResult == "PASS")
    {
      btn.Background = Brushes.SeaGreen;
      btn.Foreground = Brushes.White;
    }
    else // TstResult is "FAIL"
    {
      btn.Background = Brushes.Red;
      btn.Foreground = Brushes.White;
    }