简体   繁体   English

我如何在C#中使用textBox的KeyPress事件绑定一个CheckBox

[英]How I can bound a checkBox with KeyPress event of a textBox in C#

Hi I'm new in C# visual programming and I'm facing a problem in winform that is I want to make the textBox accepts numbers only when a checkBox is checked ... the problem is that I know how to use the code inside KeyPress event but it doesn't work with the idea of checkBox. 嗨,我是C#可视化编程的新手,我在winform中遇到一个问题,即我想使textBox仅在选中checkBox时才接受数字...问题是我知道如何在KeyPress中使用代码事件,但不适用于checkBox的想法。

I have this code: 我有以下代码:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
  if(char.IsLetter(e.Keychar))
  {
    e.Handled = true;
  }
}

Now the question is how to make this happens when a checkBox is checked??? 现在的问题是,当选中一个复选框时如何使这种情况发生???

on your key press event you could do: 在按键事件中,您可以执行以下操作:

if (this.checkBoxNumericOnly.Checked)
{
    //your code to only allow numerics...
}

Thanks to all of you .. 感谢大家 ..

I wrote this code to enter numbers but only one dot '.' 我编写此代码是为了输入数字,但只能输入一个点“。”。 and it works finally ... thanks a lot for help 终于可以了...非常感谢您的帮助

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (this.checkBox1.Checked)
        {
            e.Handled = !char.IsDigit(e.KeyChar)&&(e.KeyChar != '.') && !char.IsControl(e.KeyChar);
            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
            {
                e.Handled = true;
            }


        }
    }

Use the MaskedTextBox control and handle the checkbox event to change the mask property 使用MaskedTextBox控件并处理复选框事件以更改mask属性

 private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if(checkBox1.Checked == true)
        {
            maskedTextBox1.Mask = "000-000-0000";
        }
        else
        {
            maskedTextBox1.Mask = null;
        }
    }

Simply try this in your TextBox 's keypress event : 只需在TextBox的keypress事件中尝试以下操作:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {

            if(this.checkBox1.Checked)
            {
                //Allow only number
                if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
                {
                    e.Handled = true;
                }
            }            
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM