2011-12-28 147 views
0

我正在學習C#,所以我正在做一些習慣習慣C#語法和更好地學習的練習。我決定製作一個和普通Windows計算器相似的計算器。C#計算器按下按鍵打字

我只創建了一個按鈕「1」和一個文本框。 enter image description here

我想讓這個按鈕在文本框中寫入1,當我按下該按鈕時,還會使一個int變量等於教科書中的數字,以便稍後進行計算。所以我不能改變「int a」的值或改變文本框中的文本,它總是顯示01,因爲a總是等於0. 我怎樣才能讓程序顯示正確的數字並改變數值一個正確的? 例如,如何讓程序在文本框中顯示十一次,當我按兩次按鈕並將「int a」的值更改爲11?

public partial class Form1 : Form 
{ 
    int a; 
    string Sa; 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     Sa = a.ToString() + "1"; 

     textBox1.Text = Sa; 
    } 

    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 

    } 
} 
+3

你的問題並不清楚裏面。你知道字符串和整數之間的區別嗎?你明白a.ToString()+「1」是一個不是整數的字符串。所以它會簡單地將1連接到字符串。 – 2011-12-28 13:12:17

+0

在上一個文本之前追加文本:textBox1.Text =「1」+ textBox1.Text; – adatapost 2011-12-28 13:20:50

回答

3
private void button1_Click(object sender, EventArgs e) 
{ 
    textBox1.Text += "1"; 
} 

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    a = Int32.Parse(textBox1.Text);  
} 

只是它..更改textBox每按鈕單擊,並更改變量每個文本框更改。

2

的值可以接着使用

a = int.Parse(Sa); 
textBox1.Text = Sa.TrimStart('0'); 

但如果你想成爲它更加高效,

a = a * 10 + 1; 

沒有Sa在所有設置,

textBox1.Text = a.ToString(); 

如果遇到in泰格溢出,你應該使用BigInteger

0

您有幾種選擇:

使int爲可空int。這樣,你可以檢查是否INT已經設置

int? a; 

if (a.HasValue) 
{ 
} 
else 
{ 
} 

檢查textBox1的Text屬性爲空(這意味着你不必追加到它)

if (textBox1.Text == string.Empty) 
{ 
} 
else 
{ 
} 
0
public void btnOne_Click(object sender, EventArgs e) 
     { 
      txtDisplay.Text = txtDisplay.Text + btnOne.Text; 

     } 

     private void btnTwo_Click(object sender, EventArgs e) 
     { 
      txtDisplay.Text = txtDisplay.Text + btnTwo.Text; 
     } 

// etc 
0

爲要追加文本到文本框中任何按鈕設置點擊屬性btn_Click那麼PT這代碼的方法

private void btn_Click(object sender, EventArgs e) 
{ 
    Button btn = (Button)sender; 
    // This will assign btn with the properties of the button clicked 
    txt_display.Text = txt_display.Text + btn.Text; 
    // this will append to the textbox with whatever text value the button holds 
}