【问题标题】:How do I give a method to an object that is defined inside of a click event?如何为单击事件中定义的对象提供方法?
【发布时间】:2021-12-08 22:34:34
【问题描述】:

所以我想为txt制作一个方法,但我不知道如何。我记得它是带有“=>”运算符的东西,但我不记得正确的语法。有人能帮我吗?这是代码:

private void button1_Click(object sender, EventArgs e)
        {
            ex_y += 25;
            n = int.Parse(textBox1.Text);
            for (int i = 0; i < n; i++)
            {
                Button b = new Button();
                this.Controls.Add(b);
                b.Size = new Size(50, 50);
                b.Location = new Point(ex_x + b.Width + 25, ex_y);
                ex_x = b.Location.X;
                b.Text = rand.Next(0, 100).ToString();
                a[i] = int.Parse(b.Text);

                rand.Next(0, 100);
                TextBox txt = new TextBox();
                this.Controls.Add(txt);
                txt.Size = new Size(b.Size.Width, 50);
                txt.Location = new Point(b.Location.X, b.Location.Y + 60);
                txt.BackColor = Color.White;    

            }
        }

【问题讨论】:

    标签: c# winforms methods


    【解决方案1】:

    从技术上讲,您希望订阅该事件,这是通过 += 运算符完成的。这是official documentation

    例如:

    private void button1_Click(object sender, EventArgs e)
    {
        Button b = new Button();
        b.Click += new System.EventHandler(b_Click);
        this.Controls.Add(b);
        b.Size = new Size(50, 50);
    }
    
    private void b_Click(object sender, EventArgs e)
    {
        MessageBox.Show("I was clicked!");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-05
      • 2012-12-02
      • 2017-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多