How do I invoke the contents of the load constructor from a button?

Asked 2 years ago, Updated 2 years ago, 44 views

I don't know if it's called a constructor, but
How can I do it?
Thank you for your cooperation.

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

namespace WindowsFormsApplication1
{
    public partial class Form 1:Form
    {
        public Form 1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgse)
        {
            MessageBox.Show("hello world");
        }

        private void button1_Click(object sender, EventArgse)
        {
            // I want to call Form1_Load here
        }
    }

}

Windows 10 64-bit/Visual Studio for Desktop 2015

c#

2022-09-30 21:24

1 Answers

If you want to run the Form1_Loadmethod or Form1.LoadEvent Handler, write:

private void button1_Click (object sender, EventArgse)
{
    Form 1_Load (this, EventArgs.Empty);
}

This is grammatically equivalent to MessageBox.Show("hello world").Although the above example specifies this as the sender and e with EventArgs.Empty and "correct as API", the actual argument value can also be null because the Form1_Load method does not reference the argument value.

Note that the event handler is not intended to run directly from within the code, so a more appropriate method is to define another common method and refer to Form1_Load and button1_Click.

private void Form1_Load (object sender, EventArgse)
{
    ShowHelloWorld();
}
private void button1_Click(object sender, EventArgse)
{
    ShowHelloWorld();
}
private void ShowHelloWorld()
{
    MessageBox.Show("hello world");
}


2022-09-30 21:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.