[英]C# Multiple Forms and Panels
I have a Main Screen form set up, with it's body consisting of one giant panel. 我设置了一个主屏幕窗体,它的主体由一个巨大的面板组成。 I then have a series of User Controls which get erased or loaded into that Main Screen.
然后,我有一系列用户控件,这些用户控件被擦除或加载到该主屏幕中。 What I don't know how to do is have the User Controls affect the Main Screen.
我不知道该怎么做是让用户控件影响主屏幕。
Code Example from a User Control: 用户控件中的代码示例:
PartsSystem parts = new PartsSystem(); //a user control
MainMenu.pnlMain.Controls.Clear();
MainMenu.pnlMain.Controls.Add(parts);
This code works when loading the main screen, but I can't seem to access pnlMain from my other user controls. 加载主屏幕时,此代码有效,但是我似乎无法从其他用户控件访问pnlMain。 Is it possible to fix this?
有可能解决这个问题吗? I have a function set up to grab a user Control within the MainMenu form, but I can't seem to get it to be called from a user control.
我已经设置了一个函数,可以在MainMenu表单中获取用户控件,但是似乎无法从用户控件中调用它。 I'm trying to make it so that when they click a button, they go to the next screen (user control).
我试图做到这一点,以便当他们单击按钮时,他们进入下一个屏幕(用户控件)。
I am using C# on Windows 7 with Visual Studio 2010 and all the default settings. 我在Windows 7和Visual Studio 2010以及所有默认设置上使用C#。
Here is some additional code samples: 以下是一些其他代码示例:
public partial class Main_Menu : Form
{
public Main_Menu()
{
InitializeComponent();
MainMenuPanel main = new MainMenuPanel();
panelChange(main);
}
public void panelChange(UserControl newPanel)
{
pnlMain.Controls.Clear();
pnlMain.Controls.Add(newPanel);
}
} }
That was Main_Menu. 那是Main_Menu。 This code works on launch.
此代码在启动时有效。 Now, bringing up my PartsSystem is another issue.
现在,启动我的PartsSystem是另一个问题。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Program_v1._0._0._0._4
{
public partial class MainMenuPanel : UserControl
{
public MainMenuPanel()
{
InitializeComponent();
Main_Menu parentForm = (this.Parent as Main_Menu);
}
public void btnPartsInventory_Click(object sender, EventArgs e)
{
Main_Menu myParent = (this.Parent as Main_Menu);
PartsSystem parts = new PartsSystem();
myParent.pnlMain.Controls.Clear(); //Object reference not set to an instance of an object.
//This is the error I get at this point. It won't let me use the function.
myParent.pnlMain.Controls.Add(parts);
}
}
} }
Thank you for the help! 感谢您的帮助!
Try using UserControl.Parent
to get access the parent control. 尝试使用
UserControl.Parent
获取对父控件的访问。
access form from usercontrol 从用户控件访问表单
Get access to parent control from user control - C# 从用户控件获取对父控件的访问-C#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.