我想在C#中从ChildForm访问ParentForm的面板控件 [英] I want to access panel control of ParentForm from ChildForm in C#

查看:158
本文介绍了我想在C#中从ChildForm访问ParentForm的面板控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ParentForm上有面板控件,我在panl控件上打开了ChildForm,从ChildForm我想在ParentForm的面板控件上打开ThirdForm





i在ChildForm按钮上使用此代码



i have panel control on ParentForm, i opened the ChildForm on panl control and from ChildForm i want to open ThirdForm on panel control of ParentForm


i used this code on the button of ChildForm

ParentForm panel = new ParentForm();
panel.panel_Main.Controls.Clear();
ThirdForm third = new ThirdForm();
third.TopLevel = false;
third.AutoScroll = true;
third.Dock = DockStyle.Fill;
panel.panel_Main.Controls.Add(third);
student.Show();

推荐答案

这不会起作用:线索在 new 关键字。要访问正在显示的表单,您需要获取当前显示的实例,而不是新实例 - 新实例将与旧实例无关。把它想象成一辆汽车:如果你把你的手机放在汽车的手套箱里,然后出去购买一辆新车,你是否希望将它的手机放在它的手套箱里?



但即使这样,也不要。

这是一个糟糕的主意,因为它锁定了两种形式的设计:你不能在不考虑对外界的影响,你不能在其他任何地方重复你的孩子形式。



相反,你的孩子表格应该要求父母为此完成工作。

看看这里:在两个表格之间传递信息,第2部分:孩子到父母 [ ^ ] - 它解释了如何操作。
That isn't going to work, ever: the clue is in the new keyword. To access the form that is being displayed, you need to get the currently displayed instance, not a new instance - the new one will have nothing to do with the old. Think of it like a car: if you put your mobile phone in the glove box of your car, then go out an buy a new car would you expect it to have your mobile in it's glove box?

But even then, don't.
It's a poor idea, because it "locks" the design of the two forms: you can't make changes without considering the effects on the outside world, and you can't reuse your child form anywhere else.

Instead, your child form should ask the parent to do the job for it.
Have a look here: Transferring information between two forms, Part 2: Child to Parent[^] - it explains how to do it.


我使用它来代替我的上一个代码并且它可以工作。



i used this instead of my last code and it works.

((System.Windows.Forms.Panel)Application.OpenForms["ParentForm"].Controls["panel_Main"]).Controls.Clear();
                    ThirdForm third = new ThirdForm();
                    third.TopLevel = false;
                    third.AutoScroll = true;
                    third.Dock = DockStyle.Fill;
                  ((System.Windows.Forms.Panel)Application.OpenForms["ParentForm"].Controls["panel_Main"]).Controls.Add(student);
                    third.Show();


这篇关于我想在C#中从ChildForm访问ParentForm的面板控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆