简体   繁体   English

c#中如何使用Normal方法调用按钮点击事件?

[英]How to call button click event using Normal method in c#?

I have a method name loadTest123().我有一个方法名称 loadTest123()。 I tried to call Button1_Click event from loadTest123().我试图从 loadTest123() 调用 Button1_Click 事件。 But event not occurred.但是事件没有发生。 I am trying to debug with break point in Button1_Click event but not triggering.我正在尝试使用 Button1_Click 事件中的断点进行调试但未触发。

Eg:例如:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            loadTest123();
        }

        public Button Coke = new Button();

        public void loadTest123()
        {
            Coke.Click += new EventHandler(button1_Click);
        }

        private void button1_Click(object sender, EventArgs e)
        {
             MessageBox.Show("Hello!!!");      
        }        
    }
}

Please help me to solve this issue.请帮我解决这个问题。

what you have done is just binding of event, you have not called it. 您所做的只是绑定事件,您还没有调用它。 You have to call that event to actually run it. 您必须调用该事件才能实际运行它。

Do this, 做这个,

button1.PerformClick();

OR, 要么,

button1_Click(null, new EventArgs());

in your method. 用你的方法。

What you have in loadTest123() method is for subscribing to an event, it won't trigger subscribed method until you perform click on it. loadTest123()方法中的内容用于订阅事件,除非您单击该事件,否则它不会触发订阅的方法。

Also, you have attached button1_Click to Click event but there is no method declared with the name. 另外,您还附加了button1_Click to Click事件,但没有使用该名称声明任何方法。 You need (something) like this. 您需要这样的东西。

   private void button1_Click(object sender, EventArgs e)
   {
         MessageBox.Show("Hello!!!");      
   }        

If you are looking to perform click programatically , there is a PerfromClick method on button, you could use it. 如果您希望以编程方式执行单击,则可以使用按钮上的PerfromClick方法。

Coke.PerformClick();

You created the button but not added to controls, is this intentional? 您创建了按钮但未添加到控件中,这是故意的吗?

see below code and comments 参见下面的代码和注释

public Form1()
{
    InitializeComponent();
    loadTest123();
}

public Button Coke = new Button();

public void loadTest123()
{
    // BELOW LINE IS ONLY FOR REGISTER YOUR BUTTON'S CLICK EVENT
    Coke.Click += new EventHandler(button1_Click);

    // FIRE YOUR EVENT IN CODE BEHIND
    Coke.PerformClick();
    // OR
    button1_Click(null, new EventArgs());
}

private void button1_Click(object sender, EventArgs e)
{
     MessageBox.Show("Hello!!!");      
}        

This works for me:这对我有用:

InvokeOnClick(button, e);

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

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