Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

c# - Accessing Main Form From Child Form

I have a simple problem: I have a main form in win-forms/c#. It has a listbox bound to a database.

When I click a button a new form is created.

When I click a button on the child form, I want to call a method that exists in the main form, that updates the list box or alternatively when the child form closes, to call that function.

Is this possible??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are many ways to achieve this, but here's a simple way. In your main form, when you create and show a child form, do it like this:

ChildForm child = new ChildForm();
child.Show(this); // this calls the override that takes Owner parameter

Then, when you need to call a method in the main form from the child form, use code like this (assumes your main form is of type MainForm):

MainForm parent = (MainForm)this.Owner;
parent.CallCustomMethod();

A more complex way would be to use a form of dependency injection, where you would pass in a reference to the parent form (or more properly, to its interface) in the constructor of the child form. But the above way is simple and probably effective enough for your purposes (and it actually is a form of dependency injection itself, sort of).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...