본문 바로가기

Programming/C#-Winform

[펌]Form - Form - Usercontrol 간 데이터 전달

출처 : http://pino93.tistory.com

 

아래부분은 MainForm 에 포함된 UserControl에서 ChildForm을 호출하고
다시 ChildForm에서 MainForm에 포함된 UserControl 값을 전달한다

UserControl이 아닌 Form또한 같은 방식으로 처리하면 됨

사용자 삽입 이미지

#1 MainForm (Group Box 안에는 #2의 UserControl이 포함됨)






















 

사용자 삽입 이미지

#2 UserControl














 

1 namespace ParentForm

2 {

3 public partial class userControl : UserControl

4 {

5 public userControl()

6 {

7 InitializeComponent();

8 }

9

10 /// ChildForm 호출

11 private void btnOpen_Click(object sender, EventArgs e)

12 {

13 this.listBox.Items.Clear();

14

15 ChildForm frm = new ChildForm(this, this.textBox.Text);

16 frm.ShowDialog();

17 }

18

19 /// Child 에서 GetString 함수를 호출하기 위해 Public 정의

20 public void GetString(string str)

21 {

22 this.listBox.Items.Add(str);

23 this.listBox.SelectedIndex = this.listBox.Items.Count - 1;

24 }

25

26 }

27 }

#3 ChildForm
- UserControl 에서 ChildForm을 호출하며 다시 MainForm으로 값을 전달

사용자 삽입 이미지









 

1 namespace ParentForm

2 {

3 public partial class ChildForm : Form

4 {

5 /// 부모폼

6 public ParentForm.userControl parent = null;

7

8 public ChildForm(ParentForm.userControl p, string str)

9 : this()

10 {

11 this.txtBox.Text = str;

12

13 this.parent = p;

14 }

15

16 public ChildForm()

17 {

18 InitializeComponent();

19 }

20

21 /// 부모폼의 GetString 함수 호출

22 private void btnSend_Click(object sender, EventArgs e)

23 {

24 parent.GetString(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + this.txtBox.Text);

25 }

26 }

27 }

##################################################

사용자 삽입 이미지

1. MainForm의 FormOpen Button을 클릭하면 ChildForm을 호출한다





















 

사용자 삽입 이미지

2. ChildForm의 Send Button을 클릭하면 MainForm의 ListBox에 추가된다.