【问题标题】:How to open new user control from another user control in Visual Studio如何在 Visual Studio 中从另一个用户控件打开新用户控件
【发布时间】:2018-06-16 22:57:37
【问题描述】:

我创建了 2 个菜单(一个用于管理员,另一个用于用户)这两个菜单是用户控件,我有一个面板可以显示所有内容(其他用户控件)..

userControl 1 是:Admin_menu

Button1 : Admin_menu 中的按钮

Button2 : Admin_menu 中的按钮

userControl 3 是:content1

userControl 4 是:content2

我有一个包含两个方面的主表单: 左侧:Admin_menu 右侧:显示内容的面板

所有的用户控件都添加到主窗体

问题是:当我点击 button1 显示 content1 或 button2 显示 content2 时,我收到此消息:

Problem pic

我在 Admin_menu.cs 中的代码:

        public Admin_menu()
        {
            InitializeComponent();
        }

        private void btnTrainers_Click(object sender, EventArgs e)
        {
            Parent.Controls["trainersTab1"].BringToFront();
        }

        private void btnBranches_Click(object sender, EventArgs e)
        {
            //BranchesTab branchespage = new BranchesTab();
            //this.Parent.Controls.Add(branchespage);
            Parent.Controls["branchespage"].BringToFront();
        }

        private void btnTimeTables_Click(object sender, EventArgs e)
        {
            Parent.Controls["timeTableTab1"].BringToFront();
        }

【问题讨论】:

  • 控件trainersTab1branchespage 作为InitializeComponent 代码的一部分添加到Admin_Menu?它们是直接添加到Admin_Menu 还是它们是某些容器控件的一部分,例如Admin_Menu 中的Group Box 或Panel?您是否使用正确的控件名称来查找它们?
  • 您很可能无法通过 Parent.Controls["trainersTab1"] 获得“trainersTab”。最好使用 Visual Studio Watch 窗口来查看 Parents.Controls 中的对象 请记住,您可能需要通过控制层次结构 我最好的猜测是尝试 Parent.Controls["Admin_Menu"].Controls["trainersTab1" ].BringToFront()
  • @ChetanRanpariya 我有一个包含两个侧面的主窗体:左侧:Admin_menu 右侧:显示内容的面板所有用户控件都添加到主窗体

标签: c# asp.net visual-studio visual-studio-2012 user-controls


【解决方案1】:

很有可能

Parent.Controls["trainersTab1"]

正在返回 null。

这个答案可能会帮助您找到 trainerTab1 控件,假设该控件的名称也称为“trainerTab1”。

Get a Windows Forms control by name in C#

Control trainerTab1 = this.Controls.Find("trainerTab1", true);
if (trainerTab1 != null) trainerTab1.BringToFront();

【讨论】:

  • 它不起作用,我在这一行得到一个错误:Control trainerTab1 = this.Controls.Find("trainerTab1", true);错误:无法将类型“system.windows.forms.control[]”隐式转换为“system.windows.forms.control”
  • 抱歉,忘记了 Controls.Find 使用 System.Linq 返回 Control[] ... if (trainerTab1 != null && trainerTab1.Any()) trainerTab1.First().BringToFront();
猜你喜欢
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多