C#-在构造函数中加载方法



有人能解释为什么(在构造函数中)执行此方法会引发语法错误吗:

public partial class Form1 : Form
{
    public Form1()
    {
        Load += YourPreparationHandler;
    }
    private void YourPreparationHandler(object sender, EventArgs e)
    {
        button22_Click(sender, e);
    }
}

名称"button22_Click"不存在于当前上下文中

button22_ClickForm1的成员吗?请检查该方法是否存在,错误很容易解释。

button22_Click是否在任何地方定义?如果不是这样,那就是问题所在。

通常在构造函数中有这样的东西:

public Form1()
{
   InitializeComponent();
}

窗体类被设置为分部类。这是因为在VisualStudio中,当您将组件拖放到窗体上时,幕后VS会使用您的更新来更新设计器文件。

所以,你会有

Form1.cs

Form1.Designer.cs

可能还有

Form1.xx.resx(如果您有全球化)

如果你查看设计器文件,你会看到Visual Studio正在生成的代码:

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.buttonTest = new System.Windows.Forms.Button();
            this.textBoxPW = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.textBoxOutput = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // buttonTest

我打赌设计器文件丢失、混乱,或者InitializeComponent被意外删除。在任何情况下,对象(button_22)都不存在或未被引用,因此您将无法在其上引发单击事件。

最新更新