【发布时间】:2014-01-14 02:39:09
【问题描述】:
我设置了一个主屏幕窗体,它的主体由一个巨大的面板组成。然后,我有一系列用户控件被删除或加载到该主屏幕中。我不知道该怎么做是让用户控件影响主屏幕。
来自用户控件的代码示例:
PartsSystem parts = new PartsSystem(); //a user control
MainMenu.pnlMain.Controls.Clear();
MainMenu.pnlMain.Controls.Add(parts);
此代码在加载主屏幕时有效,但我似乎无法从其他用户控件访问 pnlMain。有可能解决这个问题吗?我设置了一个函数来获取 MainMenu 表单中的用户控件,但我似乎无法从用户控件中调用它。我正在努力做到这一点,以便当他们单击按钮时,他们会转到下一个屏幕(用户控件)。
我在带有 Visual Studio 2010 和所有默认设置的 Windows 7 上使用 C#。
这里是一些额外的代码示例:
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);
}
}
那是 Main_Menu。此代码适用于启动。现在,调出我的 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);
}
}
}
感谢您的帮助!
【问题讨论】:
-
很难说没有看到其他代码,但我建议您在创建其他控件时传递该信息。
-
如果你想看的话,我已经添加了更多代码。