본문 바로가기
📁 [4] 개발자 정보 & 코드 노트/C#

C# Windows Forms 강의 42편: UserControl로 복잡한 UI 구성

by wawManager 2025. 3. 17.

1. 강의 개요

이번 강의에서는 UserControl을 활용해 복잡한 UI를 구성하는 방법을 학습합니다.
UserControl은 여러 컨트롤을 조합하여 하나의 재사용 가능한 UI 구성 요소로 만드는 데 유용합니다.
이번 강의에서는 사용자 정보 카드를 구현하며, 동적으로 추가 및 삭제 가능한 UI를 제작합니다.


2. 학습 목표

  1. UserControl로 복잡한 UI를 설계하고 제작.
  2. 동적으로 UserControl을 추가 및 제거하는 방법.
  3. 부모 폼과 UserControl 간의 데이터 전달.

3. 요구사항

  1. 사용자 정보(이름, 나이, 이메일)를 표시하는 UserControl 제작.
  2. 부모 폼에서 버튼으로 UserControl 동적 추가 및 삭제.
  3. UserControl에 표시된 데이터는 부모 폼에서 전달받아 설정.

4. 실습: 사용자 정보 카드 UI 제작

1. UserControl 생성

  1. 솔루션 탐색기 > 프로젝트 우클릭 > 추가 > 새 항목 > User Control
  2. 파일 이름: UserCardControl.cs

2. 코드 작성

UserCardControl.cs

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class UserCardControl : UserControl
    {
        public UserCardControl()
        {
            InitializeComponent();
        }

        // 사용자 이름 속성
        private string _userName;
        [Category("Custom Properties"), Description("사용자 이름")]
        public string UserName
        {
            get => _userName;
            set
            {
                _userName = value;
                lblName.Text = $"이름: {_userName}";
            }
        }

        // 나이 속성
        private int _userAge;
        [Category("Custom Properties"), Description("사용자 나이")]
        public int UserAge
        {
            get => _userAge;
            set
            {
                _userAge = value;
                lblAge.Text = $"나이: {_userAge}";
            }
        }

        // 이메일 속성
        private string _userEmail;
        [Category("Custom Properties"), Description("사용자 이메일")]
        public string UserEmail
        {
            get => _userEmail;
            set
            {
                _userEmail = value;
                lblEmail.Text = $"이메일: {_userEmail}";
            }
        }

        // 삭제 버튼 클릭 이벤트
        private void BtnDelete_Click(object sender, EventArgs e)
        {
            this.Dispose(); // 컨트롤 제거
        }
    }
}

UserCardControl.Designer.cs

namespace WindowsFormsApp1
{
    partial class UserCardControl
    {
        private System.ComponentModel.IContainer components = null;
        private Label lblName;
        private Label lblAge;
        private Label lblEmail;
        private Button btnDelete;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.lblName = new Label();
            this.lblAge = new Label();
            this.lblEmail = new Label();
            this.btnDelete = new Button();
            this.SuspendLayout();

            // lblName
            this.lblName.AutoSize = true;
            this.lblName.Location = new System.Drawing.Point(10, 10);
            this.lblName.Name = "lblName";
            this.lblName.Size = new System.Drawing.Size(50, 20);
            this.lblName.Text = "이름:";

            // lblAge
            this.lblAge.AutoSize = true;
            this.lblAge.Location = new System.Drawing.Point(10, 40);
            this.lblAge.Name = "lblAge";
            this.lblAge.Size = new System.Drawing.Size(36, 20);
            this.lblAge.Text = "나이:";

            // lblEmail
            this.lblEmail.AutoSize = true;
            this.lblEmail.Location = new System.Drawing.Point(10, 70);
            this.lblEmail.Name = "lblEmail";
            this.lblEmail.Size = new System.Drawing.Size(50, 20);
            this.lblEmail.Text = "이메일:";

            // btnDelete
            this.btnDelete.Location = new System.Drawing.Point(150, 30);
            this.btnDelete.Name = "btnDelete";
            this.btnDelete.Size = new System.Drawing.Size(75, 30);
            this.btnDelete.Text = "삭제";
            this.btnDelete.UseVisualStyleBackColor = true;
            this.btnDelete.Click += new System.EventHandler(this.BtnDelete_Click);

            // UserCardControl
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.lblName);
            this.Controls.Add(this.lblAge);
            this.Controls.Add(this.lblEmail);
            this.Controls.Add(this.btnDelete);
            this.Name = "UserCardControl";
            this.Size = new System.Drawing.Size(250, 100);
            this.ResumeLayout(false);
            this.PerformLayout();
        }
    }
}

3. 폼에 UserControl 동적 추가

Form1.cs

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private int userCounter = 0;

        public Form1()
        {
            InitializeComponent();
            InitializeButtons();
        }

        private void InitializeButtons()
        {
            btnAddUser.Click += BtnAddUser_Click;
        }

        // "사용자 추가" 버튼 클릭 이벤트
        private void BtnAddUser_Click(object sender, EventArgs e)
        {
            // 새로운 사용자 카드 생성
            userCounter++;
            UserCardControl userCard = new UserCardControl
            {
                UserName = $"사용자 {userCounter}",
                UserAge = 20 + userCounter,
                UserEmail = $"user{userCounter}@example.com",
                Location = new System.Drawing.Point(20, 20 + (110 * (userCounter - 1))) // 카드 위치
            };

            // 폼에 추가
            this.Controls.Add(userCard);
        }
    }
}

Form1.Designer.cs

namespace WindowsFormsApp1
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;
        private Button btnAddUser;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.btnAddUser = new Button();
            this.SuspendLayout();

            // btnAddUser
            this.btnAddUser.Location = new System.Drawing.Point(20, 20);
            this.btnAddUser.Name = "btnAddUser";
            this.btnAddUser.Size = new System.Drawing.Size(150, 30);
            this.btnAddUser.Text = "사용자 추가";
            this.btnAddUser.UseVisualStyleBackColor = true;

            // Form1
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(400, 600);
            this.Controls.Add(this.btnAddUser);
            this.Name = "Form1";
            this.Text = "UserControl로 복잡한 UI 구성";
            this.ResumeLayout(false);
        }
    }
}

5. 실행 결과

  1. 폼 초기 상태
    • "사용자 추가" 버튼이 폼에 표시됩니다.
  2. 사용자 추가
    • "사용자 추가" 버튼 클릭 → 새로운 사용자 카드(UserCardControl)가 폼에 동적으로 추가됩니다.
  3. 카드 삭제
    • 사용자 카드의 "삭제" 버튼 클릭 → 해당 카드가 제거됩니다.

6. 주요 개념 요약

  1. UserControl의 활용
    • 복잡한 UI를 간단히 구성하고 재사용 가능한 컴포넌트로 제작.
  2. 동적 컨트롤 추가
    • Controls.Add()로 동적으로 UserControl을 추가하고 배치.
  3. 데이터 전달
    • 부모 폼에서 UserControl의 속성을 설정하여 데이터를 전달.