简体   繁体   中英

Getting checked radio button

I have made 4 radio buttons and set their tag to wood, diamond, clay, and brick. I want to find the checked one and set a Bitmap property based on the selected radio button. Disregard the fact that it should be split into more methods, that will be done when i refactor. The properties cellBgImage in Map and Cell are null.

 void setCellBgImage()
        {
            string cellBgImage = "";
            foreach (Control c in myMap.myForm.Controls)
            {
                if (c is RadioButton)
                {
                    RadioButton radio = c as RadioButton;
                    if (radio.Checked)
                    {
                        cellBgImage = radio.Tag.ToString();
                    }
                }
            }
            switch (cellBgImage)
            {
                case "wood":
                    myMap.cellBgImage = (Bitmap)Bitmap.FromFile("Images/wood.png");
                    break;
                case "diamond":
                    myMap.cellBgImage = (Bitmap)Bitmap.FromFile("Images/diamond.png");
                    break;
                case "clay":
                    myMap.cellBgImage = (Bitmap)Bitmap.FromFile("Images/clay.png");
                    break;
                case "brick":
                    myMap.cellBgImage = (Bitmap)Bitmap.FromFile("Images/brick.png");
                    break;
            }
            foreach (Cell cell in myMap.myCells)
            {
                cell.myBgImage = myMap.cellBgImage;
            }
        }

Add a default case to the switch so when none of them are checked you still get a value in myMap.cellBgImage.

      default:
            myMap.cellBgImage = (Bitmap)Bitmap.FromFile("Images/brick.png");
            break;

As you write at the comments your RB are in panel1. so you should do the Foreach like this:

foreach (Control c in this.panel1.Controls)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM