首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态对象中的C#对象与动态标签的连接

动态对象中的C#对象与动态标签的连接
EN

Stack Overflow用户
提问于 2018-04-28 14:40:03
回答 1查看 82关注 0票数 0

我创建了一个动态表单,并在其中创建了动态对象。但是,由于某种原因,当我创建动态事件处理程序时,事件处理程序不会获取动态对象。也就是说,它们不会出现在Visual中的下拉选项列表中。

守则:

代码语言:javascript
复制
private void btnShop_Click(object sender, EventArgs e)
    {
        Form frmShop = new Form();
        frmShop.Show();

        Button newButton = new Button();
        Button Add = new Button();
        Label Meat = new Label();
        Label Carrots = new Label();
        Label DogFood = new Label();
        Label Fish = new Label();
        Label Rainbows = new Label();

        frmShop.Controls.Add(Meat);
        frmShop.Controls.Add(Carrots);
        frmShop.Controls.Add(DogFood);
        frmShop.Controls.Add(Fish);
        frmShop.Controls.Add(Rainbows);

        frmShop.Controls.Add(newButton);
        frmShop.Controls.Add(Add);

        frmShop.Size = new Size(300,300);

        //HERE IS MY PROBLEM v //
        frmShop.Controls.Add(lblCount) 
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-28 14:54:29

变量彩虹是btnShop_Click事件处理程序的本地变量,即使使用相同的名称,也不能在其他方法中使用该变量。在这里了解范围界定

您需要将控件移动到全局范围,或给它们命名并从窗体控件集合中检索它们。

例如,将接收动态表单的变量移动到全局范围(在任何类方法之外,但在类声明中)。

代码语言:javascript
复制
private Form frmShop = null;

private void btnShop_Click(object sender, EventArgs e)
{
    frmShow = new Form();
    .....

    // Set the Name property for the label
    Label Rainbow = new Label { Name = "Rainbow" }
    ...

    frmShow.Controls.Add(Rainbow);


}

protected void newButton_Click(object sender, EventArgs e)
{
    ...

    // Try to extract the label required from the form controls collection
    // using the specified name
    Label aRainbowLabel = frmShow.Controls
                                 .OfType<Label>()
                                 .FirstOrDefault(x=>x.Name=="Rainbow");
    aRainbowLabel.Text = "Rainbows: 1";
} 

小心,你走的是一条危险的道路。变量frmShow是全局的,如果再次单击相同的按钮,您将创建第二个具有相同元素的表单。如果这是正常的,那么没有问题,但是如果您只想要这种类型的一种形式,则需要在创建表单之前检查变量是否为null,如果关闭该表单,则需要将变量frmShow设置为null。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50077678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档