可以访问用户从母公司控制的控制 - C# [英] Get access to parent control from user control - C#

查看:146
本文介绍了可以访问用户从母公司控制的控制 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何获得在C#(WinForm的)用户控件的父控件。我使用下面的code,但它并不适用于所有类型的控件,如列表框。

How do I get access to the parent controls of user control in C# (winform). I am using the following code but it is not applicable on all types controls such as ListBox.

Control[] Co = this.TopLevelControl.Controls.Find("label7", true);
Co[0].Text = "HelloText"

其实,我必须在列表框放在父形式从用户控件添加物品。

Actually, I have to add items in Listbox placed on parent 'Form' from a user control.

推荐答案

您可以用得到父控件 Control.Parent

所以,如果你有 this.Parent 放置在窗体上的控制将是你的表格。

So if you have a Control placed on a form this.Parent would be your Form.

在你的控制,你可以做

Form parentForm = (this.Parent as Form);

更多信息


  • MSDN:Control.Parent物业

  • More Information

    • MSDN: Control.Parent Property
    • 我的控制和一个列表框(listBox1中)都是一个窗体(Form1)上进行。我必须在listBox1中增加项目时用户preSS摆在我的控制按钮。

      My Control and a listbox (listBox1) both are place on a Form (Form1). I have to add item in a listBox1 when user press a button placed in my Control.

      您的两个可能的方法来完成这件事。

      You have two possible ways to get this done.

      1。使用`Control.Parent

      的MyUserControl

          private void button1_Click(object sender, EventArgs e)
          {
              if (this.Parent == null || this.Parent.GetType() != typeof(MyForm))
                  return;
      
              ListBox listBox = (this.Parent as MyForm).Controls["listBox1"] as ListBox;
              listBox.Items.Add("Test");
          }
      

      2


      • 把财产公共MyForm的ParentForm {搞定;组; } 你的用户控件

      • 设置该属性在表单中

      • 假设你的的ListBox 被命名为 listBox1中,否则更改名称

      • put a property public MyForm ParentForm { get; set; } to your UserControl
      • set the property in your Form
      • assuming your ListBox is named listBox1 otherwise change the name

      MyForm的

      public partial class MyForm : Form
      {
          public MyForm()
          {
              InitializeComponent();
              this.myUserControl1.ParentForm = this;
          }
      }
      

      的MyUserControl

      public partial class MyUserControl : UserControl
      {
          public MyForm ParentForm { get; set; }
      
          public MyUserControl()
          {
              InitializeComponent();
          }
      
          private void button1_Click(object sender, EventArgs e)
          {
              if (ParentForm == null)
                  return;
      
              ListBox listBox = (ParentForm.Controls["listBox1"] as ListBox);
              listBox.Items.Add("Test");
      
          }
      }
      

      这篇关于可以访问用户从母公司控制的控制 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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