开发者

What is the best practice for communicating forms?

When I need to pass some information from a form to another I usually do the following:

Form2 form = new Form2(this);
form.ShowDialog();

And inside Form2.cs, I use a constructor like:

private Form1 parent;
public Form2(Form1 form)
{
   ...
   parent = form;
}

This way I can get a information from a textbox doing parent.textbox1.Text only if textbox1 is not a private member from Form1. Ok, a lot of time I need to get information about controls in Form1, should I make the setters and getters for each attribute of a control needed in Form2? For example: I need to know the开发者_JS百科 values of Text, ReadOnly and Location. Should I make the setters and getters for each one of these attributes? Is the use of internal modifier a bad practice?


The correct way to do it is with delegates. They are really pretty simple but it takes awhile to get your head around them. Here is a great example of what I think you're looking for: http://samgaut.blogspot.com/2007/11/use-delegates-to-pass-data-between.html


Since I am not allowed to add comments to answers I'm going to add this.

The linked blog post from the accepted answer does not make sense to me (could just be my lack of thorough understanding of delegates).

If the next-in-line form frmDestination has a publicly accessible setter method (SetCustomerID(string strCustID)), then why do you need to pass that into a delegate when you can just pass customerID directly to the setter?

I noticed he mentioned that

Basically, the member variable that is set within the delegate method will be populated before the Form_Load event is executed. If you notice the delegate call is executed before the frmDestination.Show() call is made. This way, you have that variable available to execute in your Form_Load processing.

Would just calling dest.SetCustomerID(customerID) before dest.Show() not do the same thing?


Seeing as this is not a reusable framework from what I can tell, I wouldn't create wrapper properties around the control properties.

If there was something that needed to be flexible about this parent form then the proper course might be to use an interface that specifies the particular controls exist or a specific base form class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜