2017-07-15 10 views
0

我想用c#開發一個計算器,並且我不使用方法單擊從0到9的所有按鈕我想我只有一個方法,並且如果單擊使用發件人和標籤在文本框中寫入的每個按鈕。 問候如何在c#中使用發件人和標籤?

enter code here 
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 Final 
{ 
public partial class Form1 : Form 

{ 
bool names; 
int counter; 
string name; 
double ans, num; 
public Form1() 
{ 
InitializeComponent(); 
} 
private void button1_Click(object sender, EventArgs e) 
{ 
Environment.Exit(0); 
} 
private void button6_Click(object sender, EventArgs e) 
{ 
textBox1.Text += "1"; 
counter++; 
again(); 
} 
private void button7_Click(object sender, EventArgs e) 
{ 
textBox1.Text += "2"; 
counter++; 
again(); 
} 

private void button8_Click(object sender, EventArgs e) 
{ 
textBox1.Text += "3"; 
counter++; 
again(); 
} 
+3

你嘗試過什麼了嗎? –

+0

我寫的所有按鈕時,單擊文本框寫這個方法,但我想只是有一種方法,我命名標籤屬性中的所有按鈕 – Yousra

+0

然後將您的代碼添加到問題 –

回答

2

你可以對所有的數字按鈕只是一個處理程序,然後您可以提取像這樣的價值:

int num = int.Parse(((Button)sender).Text); 

這假定您設置的按鈕在Text財產:0,1,2..9

您可以訪問Tag屬性就像Text

var txt = ((Button)sender).Tag).ToString(); 
textBox1.Text += txt; 
+0

謝謝,怎麼可以調用這個標籤?因爲我寫了那裏的按鈕名稱 – Yousra

+0

請看修改後的回答 –

+0

謝謝....... :) – Yousra

1

.Tag設置爲對應的值,然後通過將其轉換爲Button類型從發件人檢索它。

private void button_Click(object sender, EventArgs e) 
{ 
    var button = (Button)sender; 
    textBox1.Text += button.Tag.ToString(); 
    counter++; 
    again(); 
} 

public Form1() 
{ 
    InitializeComponent(); 

    button1.Tag = 1; 
    button1.Click += button_Click; 

    button2.Tag = 2; 
    button2.Click += button_Click; 

    // and so on for other buttons 
} 
+0

謝謝:),爲每個按鈕編寫或者只寫這一切? – Yousra

+0

使用一個'button_Click'方法作爲'Click'事件處理程序的所有按鈕 – Fabio

+0

謝謝....... :) – Yousra

相關問題