2014-10-30 69 views
0

我試圖從兩個TextBox字段獲取數據,並使用一個簡單的按鈕將它們添加到第三個TextBox。它可以輕鬆完成。文本框難度

我被卡住的地方就是這樣的場景。該按鈕可能會首先被禁用,因爲文本字段中沒有提供任何內容,並且在用戶鍵入文本字段中的任何數字時啓用該按鈕。

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 

     if (textBox1.Text != null) 
     { 
      button1.Enabled = true; 
     } 
     else 
     { 
      button1.Enabled = false; 
     } 
    } 
    private void button1_Click(object sender, EventArgs e) 
    { 
     int a = Convert.ToInt32(textBox1.Text); 
     int b = Convert.ToInt32(textBox2.Text); 
     textBox3.Text = (a + b).ToString(); 
    } 
} 
+1

移動你的「授權碼」的私有方法。從文本框上的更新處理程序調用此方法。 – 2014-10-30 02:28:27

+0

如果您對答案感到滿意,請接受它。乾杯! – 2014-10-30 10:17:00

回答

1

類似的東西應該做的伎倆(但它不是很優雅):

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 

     this.SetButtonEnableState(); 
    } 

    private void SetButtonEnableState() 
    { 
     button1.Enabled = !(string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text)); 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     int a = Convert.ToInt32(textBox1.Text); 
     int b = Convert.ToInt32(textBox2.Text); 
     textBox3.Text = (a + b).ToString(); 
    } 

    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
     this.SetButtonEnableState(); 
    } 

    private void textBox2_TextChanged(object sender, EventArgs e) 
    { 
     this.SetButtonEnableState(); 
    } 
} 

更新:

在你的情況,你可能要檢查如果文本框的值實際上是int值,如果是這種情況,那麼啓用按鈕。那麼爲什麼不用這個更新上面的方法呢?

private void SetButtonEnableState() 
    { 
     int n; 

     button1.Enabled = int.TryParse(textBox1.Text, out n) && int.TryParse(textBox2.Text, out n); 
    } 
0

我不知道爲什麼你把你的代碼Form1下,形式加載後的代碼只會激活。要解決這個問題,您首先需要創建一個textBox1_TextChange事件。不要忘記禁用該屬性中的按鈕。 enabled=false 像這樣:

private void textBox1_TextChanged(object sender, EventArgs e) 

你把你的事件塊上寫的代碼。

當2個文本框已經有數字時觸發按鈕。使用此:

選擇兩個文本框和事件標籤旁的特性尋找KeyPress然後將其命名爲numbersTB_KeyPress

private void numbersTB_KeyPress(object sender, KeyPressEventArgs e) 
     { 
      if (sender as TextBox != null) 
      { 
       if (char.IsDigit(e.KeyChar)) 
        button1.Enabled = true; 
       else 
        button1.Enabled = false; 
      } 
     }