2013-03-08 21 views
0

這是我的代碼,由於某種原因,按鈕2不會觸發,按鈕1會發生,當我將按鈕2中的代碼放入一個代碼中時,它會在其中工作。我錯過了關於獲取按鈕一和二的語法的問題,它們都可以用於點擊?我大約花了2周的時間學習c#,所以這對我來說都是新的,我不明白爲什麼這個代碼不應該工作。在C#中讀取文件的程序:Button not working

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; 

namespace WindowsFormsApplication2 
{ 

    public partial class Form1 : Form 
    { 
     string filePath = null; 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     //Method to check database connection 
     private void button1_Click(object sender, EventArgs e) 
     { 
      MessageBox.Show("button1.Click was raised."); 
     } 

     //Method to select a file 
     private void button2_Click(object sender, EventArgs e) 
     { 
      OpenFileDialog file = new OpenFileDialog(); 
      if (file.ShowDialog() == DialogResult.OK) 
      { 
       filePath = file.FileName; 
      } 
     } 
    } 
} 
+2

你有沒有指定的單擊事件到button2_Click方法? – Steve 2013-03-08 21:12:07

+1

發佈的代碼不完整,沒有分配事件的跡象。該程序使用'.designer.cs'文件,該文件未發佈,因此我們無法爲您提供幫助。 – 2013-03-08 21:14:26

回答

1

我假設事件處理程序沒有訂閱(再)。因此,請查看自動生成的文件Form1.Designer.cs中的部分類Form1。必須有這樣的地方:

this.button1.Click += new System.EventHandler(this.button1_Click); 
// is this missing? 
this.button2.Click += new System.EventHandler(this.button2_Click); 

How to: Subscribe to and Unsubscribe from Events (C# Programming Guide)

+0

謝謝,我不知道我必須在designer.cs文件中註冊所有這些事件處理程序。這是保持代碼清潔的非常酷的方式。我真的喜歡c# – 2013-03-08 23:44:02

+0

@ZachM .:通常它們會自動添加,例如,當您雙擊按鈕時。但是,也許你已經重新命名了它。請注意,你不應該使用designer.cs來初始化你的控件,因爲它是一個自動生成的文件。您的更改可以被覆蓋。 – 2013-03-08 23:48:56

0

確保button2被綁定。

從設計人員,選擇按鈕,然後轉到屬性窗口。點擊閃電,並確保點擊事件綁定到button2_Click

另一種方法是在InitializeComponent()右擊並選擇「轉到定義」(帶給您Form1.designer.cs),並查找以下:

button2.OnClick += new EventHandler(button2_Click); 

如果您已確認它的約束,我們需要看看你已經展示的更多信息來確定問題。