본문 바로가기
C#/윈폼

사용자 정의 컨트롤러

by hoshi03 2024. 9. 21.

프로젝트에 사용자 정의 컨트롤을 추가

 

추가한 도구 상자에서 원하는 위젯을 가져다가 넣어두고 빌드하면

윈폼창의 도구상자에서 만들어둔 컨트롤을 가져다가 사용 가능하다

 

이런 식으로 만들어 둔 걸 윈폼에서 사용자 정의 컨트롤을 가져와서 사용하려고 할때 

접근 지정자 문제로 바로 컨트롤의 위젯에 접근은 불가능하다

유저 컨트롤러에서 프로퍼티로 접근할 수 있게 해주자

        public string label1text
        {
            get
            {
                return label1.Text;
            }

            set
            {
                label1.Text = value;
            }
        }

 

사용할 폼에서 위에 만들어둔 프로퍼티를 이용해서 접근할 수 있다

        private void Form1_Load(object sender, EventArgs e)
        {
            userControl11.label1text = "hi";
            userControl12.label1text = "hello";
        }

 

• 버튼 이벤트 외부에서 제어하기

 

사용자 정의 컨트롤러에 이벤트 핸들러를 생성

외부에서 btn3을 클릭하면 이벤트가 발생한 것을 알려주기 위해 handler(sender,e)로 이벤트 핸들러에게 신호를 보낸다

 

namespace userController
{
    public partial class UserControl1 : UserControl
    {

        public EventHandler myClick;
        
        public UserControl1()
        {
            InitializeComponent();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            EventHandler handler = myClick;
            if (handler != null)
            {
                handler(sender, e);
            }
        }
    }
}

 

이벤트를 발생시킬 폼에서는 이벤트 핸들러 신호가 오면 실행할 메서드를 등록해둔다

namespace userController
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            userControl11.myClick += new EventHandler(btnEvent);
        }

        private void btnEvent(object sender, EventArgs e)
        {
            MessageBox.Show("외부 이벤트 !");
        }
    }
}

 

'C# > 윈폼' 카테고리의 다른 글

윈폼 CRUD  (0) 2024.09.25
mssql 윈폼 연동  (1) 2024.09.25
단일 프로세스  (0) 2024.09.21
이벤트  (0) 2024.09.21
윈폼 datatable, dataset, datagridview  (0) 2024.09.21