c#winform实现在textbox1中输入,textbox2上会自动显示1减textbox1的值

同样在textbox2中输入一个数,textbox1上会自动显示1减textbox2的值(textbox1的值加textbox2的值等于1)
求大神解答,我打的代码总是出错,麻烦帮我看看
界面如下:图片说明
代码如下:
private void textBox1_TextChanged(object sender, EventArgs e)
{
double a = Convert.ToDouble(textBox1.Text);
if (a > 1 || a < 0)
{
MessageBox.Show("alpha值为非负数且不能大于1");
}
else
{
this.textBox2.Text = Convert.ToString(1 - Convert.ToDouble(textBox1.Text));
}

    }

    private void textBox2_TextChanged(object sender, EventArgs e)
    {

        double a = Convert.ToDouble(textBox2.Text);
        if (a > 1 || a < 0)
        {
            MessageBox.Show("beta值为非负数且不能大于1");
        }
        else
        {
            this.textBox1.Text = Convert.ToString(1 - Convert.ToDouble(textBox2.Text));
        }

    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e) //设置textbox1只能输入数字
    {
        if (e.KeyChar == 0x20) e.KeyChar = (char)0;  //禁止空格键
        if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return;   //处理负数
        if (e.KeyChar > 0x20)
        {
            try
            {
                double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
            }
            catch
            {
                e.KeyChar = (char)0;   //处理非法字符
            }

        }
    }

    private void textBox2_KeyPress(object sender, KeyPressEventArgs e) //设置textbox2只能输入数字
    {
        if (e.KeyChar == 0x20) e.KeyChar = (char)0;  //禁止空格键
        if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return;   //处理负数
        if (e.KeyChar > 0x20)
        {
            try
            {
                double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
            }
            catch
            {
                e.KeyChar = (char)0;   //处理非法字符
            }

        }
    }
查看全部
lzs40
lzs40
2016/07/13 16:48
  • 点赞
  • 收藏
  • 回答
    私信

2个回复