gpt4 book ai didi

c# - 从用户控件访问父控件 - C#

转载 作者:IT王子 更新时间:2023-10-29 04:13:44 24 4
gpt4 key购买 nike

如何在 C# (winform) 中访问用户控件的父控件。我正在使用以下代码,但它不适用于所有类型的控件,例如 ListBox。

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

实际上,我必须通过用户控件将项目添加到放置在父“窗体”上的列表框中。

最佳答案

描述

您可以使用Control.Parent 获取父控件。

示例

因此,如果您在表单上放置了一个控件,this.Parent 就是您的表单。

在你的控制范围内你可以做

Form parentForm = (this.Parent as Form);

更多信息

在 Farid-ur-Rahman 发表评论后更新(他在问这个问题)

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.

您有两种可能的方法来完成此任务。

<强>1。使用`Control.Parent

示例

我的用户控件

    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.

  • 放置一个属性public MyForm ParentForm { get;放; } 到你的 UserControl
  • 在您的表单中设置属性
  • 假设您的 ListBox 被命名为 listBox1 否则更改名称

示例

我的表单

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

我的用户控件

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# - 从用户控件访问父控件 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8820606/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com