【问题标题】:how to call user control from another user control in c#? [duplicate]如何在 C# 中从另一个用户控件调用用户控件? [复制]
【发布时间】:2018-03-08 09:42:34
【问题描述】:

我在从另一个用户控件调用用户控件时遇到一个问题,我的代码如下:

 public UserControl1()
        {
            InitializeComponent();
}

        private void commandBarButtonInsert_Click(object sender, EventArgs e)
        {


            UserControl2 usr2 = new UserControl2();
            this.Hide();
            this.Parent.Controls.Add(usr2);
}

它正在返回此错误:

System.NullReferenceException:对象引用未设置为实例 一个对象

。我该如何解决这个问题?

【问题讨论】:

标签: c# winforms user-controls telerik


【解决方案1】:

问题是您没有尝试将控件添加到父级(可能是 Form1),而是尝试将 UserControl2 添加为 UserControl1 的父级。这是不可能的。

又快又脏会是这样的:

        UserControl2 usr2 = new UserControl2 ();
        this.Hide();
        Form1 parentForm = (this.Parent as Form1);

        parentForm.Controls.Add(new usr2());

【讨论】:

  • 我不能使用 Form。我只能在我的应用程序上使用用户控件。
  • @SezerErdogan 你的层次结构是什么样的?哪个控件是哪个控件的父级?
  • UserControl1 是我的父控件
  • @SezerErdogan 您想将 Control2 添加到 Control1 吗?然后使用 this.Controls.Add(usr2);
【解决方案2】:

尝试使用x:Name 引用控件,如果它们在同一个 XAML 文件中,则使用指定的名称访问它们。
编辑:另外,如果你得到一个NullReferenceException,问题就在于你在NULL对象上调用一个方法。

【讨论】:

    【解决方案3】:

    this.Parent 为 null,基本的 form 没有父级,但 panel,例如,可能有 `Parent 属性。

    另外,如果您想做this.Controls.Add(usr2); 之类的操作,您将得到System.ArgumentException,因为您无法将表单添加到另一个表单(没有任何容器)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多