C#

022_Radiobutton & GroupBox

iwannabebackendexpert 2022. 3. 30. 02:16

RadioButton 과 GroupBox를 이용해 위의 사진과 같이 만들어보자.

1. GroupBox를 끌어와 Text를 국적 / 성별로 수정 

2. RadioButton을 끌어와 모양창에 Text를 각각 대한민국, 일본, 중국, 그 외 국가로 변경

 + 디자인 창의 Name또한 rbKorea , rbJapan ,  rbChina ,rbOthers. 로 변경

 + 성별도 rbMale,rbFemale 로 변경

Radion Button : 체크박스 와 마찬가지로 하나만 체크될수있음. Checked 속성이 있으며 체크되면 CheckedChanged

이벤트를 발생한다.

private void button1_Click(object sender, EventArgs e)
        {
            RadioButton[] rbNation = { rbKorea, rbJapan, rbChina, rbOthers };
            RadioButton[] rbSex = { rbMale, rbFemale };

            string result = "";
            foreach (RadioButton rb in rbNation)
            {
                if (rb.Checked)
                {
                    result += "국적 : " + rb.Text + "\n";
                    break;
                }
            }
            foreach (RadioButton rb in rbSex)
            {
                if (rb.Checked) result += "성별 : " + rb.Text;
            }
            MessageBox.Show(result,"Result");
        }

1. RadioButton[] rbNation /  rbSex 생성 및 초기화

2. 결과값을 받기위해 string의 result 생성

3. foreach문을 통해 rbNation의 국가가 Checked 되었다면 result에 값을 추가합니다.

 + 성별도 마찬가지로 rbSex가 Checked 된 값을 result에 추가합니다.

* 국적 foreach문에서 break; 인 이유는 RadioButton은 어차피 한가지 값만 받기때문에 배열을 순차적으로 조회하다가 Checked된 값이 있으면 바로 Break로 나와 효율적으로 하기 위함.

4. MessageBox를 통해 값 출력

'C#' 카테고리의 다른 글

024_scrollBar  (0) 2022.03.30
023_ScoreCalculator  (0) 2022.03.30
021_CheckBox  (0) 2022.03.30
020_Labels  (0) 2022.03.30
019_BasicControl  (0) 2022.03.30