2014-05-14 26 views
-2

這是一個noob問題,但我試圖使用一個字符串(myButton),它是根據調用該方法的按鈕設置的,並試圖在內部使用該字符串一個參數,但我的IDE認爲我直接使用字符串。這裏是代碼:在參數中使用字符串

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 GMA 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 
      string myButton;//Currently selected button 

      private void button1_Click(object sender, EventArgs e)//This will be replicated for every button on the Form 
      { 
       myButton = "button1"; 
       SoundRoute(); 
      } 

      public void SoundRoute() 
      { 
       if ((myButton).Text == string.Empty)//This is the line I'm having trouble with. I want the string of myButton to be converted to button1, button2, etc. 
       { 
       SoundCall subForm = new SoundCall(); 
       subForm.Show(); 
       } 
      } 
    } 
} 

我會很感激任何幫助。我知道我可以爲每個按鈕製作一個新的按鈕,但這對於實際學習來說同樣重要。我已經找遍了所有的答案,但沒有運氣。

+0

「我的IDE認爲我在直接使用字符串」是什麼意思?而不是什麼? –

+1

@BenAaronson看起來OP試圖將一個包含'「button1」'的字符串轉換爲表單上的'button1'的實例,這導致了混淆。 –

+0

IDE給你一個關於你的代碼出現問題的非常具體的錯誤信息。即使你不瞭解它,你絕對沒有理由沒有把它包含在你的問題中。特定的錯誤信息比「我的IDE認爲我直接使用字符串」更容易理解。如果你需要幫助,*提供你已經擁有的信息*所以我們也會收到。 –

回答

3

使用sender參數,並將它傳遞給你的SoundRoute方法..這其實就是它:

public void SoundRoute(object sender) 
{ 
    if (((Button)sender).Text == string.Empty)//This is the line I'm having trouble with. I want the string of myButton to be converted to button1, button2, etc. 
    { 
     SoundCall subForm = new SoundCall(); 
     subForm.Show(); 
    } 
} 

然後您的活動成爲:

private void button1_Click(object sender, EventArgs e)//This will be replicated for every button on the Form 
{ 
    SoundRoute(sender); 
} 

然後,你可以有一個事件,所有按鈕連線到(因爲它「將被複製爲表單上的所有按鈕」)。

+0

+1。我提交了大約30次擊鍵和鼠標點擊提交幾乎相同的答案(包括最後一段中的信息)。您要麼輸入得更快,要麼更快看到它幾秒鐘。 :-) –

+0

......好吧,我不喜歡吹牛...但是我上週的時速爲119WPM,精度達到了100%:P(隨機辦公打字比賽..:D) –

+0

像魅力一樣工作!感謝您的幫助,我一直堅持這個多年。 – user3638674