文本框难度

时间:2014-10-30 02:21:58

标签: c# winforms

我正在尝试从两个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();
    }
}

2 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分: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;
            }
        }