(转载)C#:Form1_Load()不被执行的三个解决方法

我的第一个c#练习程序,果然又出现问题了。。。在Form1_Load() not work。估计我的人品又出现问题了。

下面实现的功能很简单,就是声明一个label1然后,把它初始化赋值为hello,然后点击它的时候,它显示改为world。

代码如下:

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

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

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "hello";
        }

        private void label1_Click(object sender, EventArgs e)
        {
            label1.Text = "world";
        }
    }
}

然后按F5进行调试,运行后弹出页面显示label1控件的文字还是label1,而不是hello,点击之后显示world,说明上面标志的那句赋值无效。

问题产生的原因:代码中的Form1_Load()方法不是自动生成的,而是自己手动写的。所以里面有些配置没修改,导致Form1_Load()无效

下面介绍三个解决方案:

解决方法一: 删除这个方法,然后到设计界面那里,双击界面后,会发现自动生成了Form1_load(),然后再进行代码编写。

解决方法二: 增加一句代码,如下

  public Form1()
  {
        InitializeComponent();
        this.Load += new EventHandler(Form1_Load);

  }

  这样,自己手动写的Form1_Load()就有被执行了。

解决方法三:

将代码进行下面修改:

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

namespace Demo1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            label1.Text = "hello";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //label1.Text = "hello";
        }

        private void label1_Click(object sender, EventArgs e)
        {
            label1.Text = "world";
        }
    }
}

这样也能想要的效果了。@_@|||

注:如果要修改控件的属性的话,直接在控件的属性那里进行修改就行。

---------------------
作者:lmei
来源:博客园
原文:https://www.cnblogs.com/lmei/p/3481988.html

 
原文地址:https://www.cnblogs.com/vuciao/p/10586734.html