【问题标题】:Add function to dynamic button in C#在 C# 中为动态按钮添加功能
【发布时间】:2016-07-17 16:35:50
【问题描述】:

我动态创建了一个表单,并在其中创建了一个按钮,但是当我尝试将我的函数添加到按钮时,它会出现以下错误:

需要方法名称。

我正在使用以下代码:

        {
        ...
        Form newForm = new Form();
        newform.Size = new Size(477, 222);
        Button btn = new Button();
        btn.Size = new Size(121, 23);
        btn.Location = new Point(231, 102);
        btn.Text = "Text";
        btn.Click += new EventHandler(Funct(label1.Text, label12.Text));
        newForm.Controls.Add(btn);
    }

    public void Funct(string stringA, string stringB)
    {
        StreamWriter write = new StreamWriter(path);
        write.WriteLine(stringA + "-" + stringB);
        write.Close();
    }

我可以做些什么来解决这个问题?

【问题讨论】:

    标签: c# forms function events button


    【解决方案1】:

    使用 lambda,将点击事件改为

    btn.Click += (s, e) => { Funct(label1.Text, label12.Text) };
    

    【讨论】:

      【解决方案2】:

      问题是 Funct 不符合 Click 事件的签名:

      试试:

      public void Funct(object sender, EventArgs e) { ... }

      如果您想动态传递字符串,您可能必须创建自己的 EventArgs 类,在其中添加其他属性。

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-08
        • 1970-01-01
        • 1970-01-01
        • 2011-12-24
        • 1970-01-01
        • 1970-01-01
        • 2013-07-10
        • 1970-01-01
        相关资源
        最近更新 更多