2014-10-30 32 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; 
      } 
     }