简体   繁体   English

动态地向用户控件添加控件

[英]Adding controls to User Controls dynamically

I want to add a control to a user control in an event handler (like a button click event). 我想在事件处理程序(如按钮单击事件)中向用户控件添加控件。

I'm trying to add a datagridview lookup control dynamically, but I couldn't get that to work, so I tried just adding a button with this code: 我正在尝试动态添加datagridview查找控件,但我无法使其工作,所以我尝试添加一个带有此代码的按钮:

private void btnCreateNewButton_Click(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.Location = new Point(100, 640);
    btn.Size = new Size(100, 30);
    btn.Text = "Click Me";
    btn.Click += (s, ea) => MessageBox.Show("New button clicked");
    this.Controls.Add(btn);
}

When i click my Create New Button, no button appears. 当我单击“创建新按钮”时,不会显示任何按钮。

If I add the exact same code into a form instead of a usercontrol, the button is created and displays as intended, but in a user control nothing happens. 如果我将完全相同的代码添加到表单而不是用户控件中,则会创建按钮并按预期显示,但在用户控件中没有任何反应。 In the user control I've also tried 在用户控件中我也试过了

this.Parent.Controls.Add(btn) and
this.ParentForm.Controls.Add(btn) 

but to no avail. 但无济于事。

Anybody got any ideas? 有人有任何想法吗?

Thanks, Ciaran. 谢谢,Ciaran。

You place your button on 100,640 point. 您将按钮放在100,640点上。 Please ensure that your user control can accomodate your dynamic button. 请确保您的用户控件可以容纳您的动态按钮。 Otherwise, you won't see it. 否则,你不会看到它。 I used your code and it worked fine for me, just ensure the proper size of both parent form and user control. 我使用了你的代码,它对我来说很好,只需确保父表单和用户控件的正确大小。

Most likely it is just that your button is being placed out of the bounds of the parent control and/or behind another control. 很可能只是你的按钮被放置在父控件的边界之外和/或在另一个控件之后。 I don't believe that UserControls or Forms are special in respect to adding controls at run-time, but a simple difference may be that Forms are by default re-sizable whereas UserControls aren't? 我不认为UserControls或Forms在运行时添加控件方面是特殊的,但一个简单的区别可能是默认情况下Forms是可重新调整大小而UserControls不是吗? Either way I don't think either Control type will automatically resize to fit all their child controls, so it's quite easy to put a new/dynamic control in the wrong place and have it not be visible. 无论哪种方式,我都不认为Control类型会自动调整大小以适应所有子控件,因此将新的/动态控件放在错误的位置并使其不可见非常容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM