2015-06-10 75 views
0

我想在窗體中創建交互式故事並將選項連接到按鈕。所以,我會像...將選項連接到按鈕

 richTextBox1.Text = "Would you like to... 
          1. Kill a dragon? 
          2. Run away? 
          3. Talk to a dragon." 

     if (button choice) 
     {} 

     if else (button choice) 

     {} 

     else (button choice) 
     {} 

然後,我有我的表格上3個按鈕命名爲1,2,3,我如何使用這些按鈕來做出選擇的程序?

+0

你只需要用上面的代碼來實現一個方法,該方法需要一個參數'int buttonChoice'。然後從按鈕點擊事件中調用該方法。 –

回答

1

試試這樣說:

public Form1() 
{ 
    InitializeComponent(); 
    button1.Click += button_Click; 
    button2.Click += button_Click; 
    button3.Click += button_Click; 
} 

和:

private void button_Click(object sender, EventArgs e) 
{ 
    Button btn = sender as Button; 
    if (btn.Name == "button1") 
    { 
     // do something here according to.. 
    } 
    else if (btn.Name == "button2") 
    { 
     // do something here according to.. 
    } 
     .... 
} 
3

給予他們相同的點擊處理程序,然後檢查sender以確定哪個按鈕被點擊

+0

我想這樣var btn = sender as Button; if(btn!= null) if(btn == btn1)但它不起作用 –

+0

@SergZ。所有關閉的按鈕都將被實例化,因此沒有任何按鈕會變爲null。 –

0

看起來應該如:

private void btns_Click(object sender, EventArgs e) 
    { 
     var btn = sender as Button; 
     if(btn == btn1) 
     { 
      MessageBox.Show("Choice 1"); 
     } 
     else if (btn == btn2) 
     { 
      MessageBox.Show("Choice 2"); 
     } 
     else if (btn == btn3) 
     { 
      MessageBox.Show("Choice 3"); 
     } 
    }