我的第一個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"; } } }
這樣也能想要的效果了。@_@|||
注:如果要修改控件的屬性的話,直接在控件的屬性那里進行修改就行。