问题描述
我想为两个以上的文本框调用一个通用函数,这样keypress就可以检查只有浮点数可以输入。
这是我的示例代码:这仅适用于单个文本框( 完成后,转到 如果您不希望在验证失败的情况下触发 I want to call a common function for more than 2 textboxes so that keypress can check that only floating point number can take a input. This is my sample code: this work only for a single textbox ( Thanks in advance. You can simply create your own control, inheriting the When done, go to the If you don't want the 这篇关于如何编写按键功能的普通功能检查在C#中的文本框的浮动数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! tbL1Distance
)。但是我想把它作为一个普通的文本框控件。
pre prerivate $ {private void tbL1Distance_KeyPress(object sender,KeyPressEventArgs e)
{
char ch = e.KeyChar;
if(ch == 46& tbL1Distance.Text.IndexOf('。')!= -1)
{
e.Handled = true;
return; ($!
)
if(!Char.IsDigit(ch)&& ch!= 8& ch!= 46)
{
e。 Handled = true;
$ b $ p
$你可以简单的创建你自己的控件,继承 TextBox
,你可以重载<$ c
$ p $ public class CustomTextBox:System.Windows.Forms.TextBox
$ b保护覆盖无效OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
char ch = e.KeyChar; (ch == 46&& this.Text.IndexOf('。'!!= -1)//用'this'替换'tbL1Distance'来引用当前的TextBox。
{
e.Handled = true;
else if(!Char.IsDigit(ch)&& ch!= 8& ch!= 46)
{
e.Handled = true ;
}
base.OnKeyPress(e);
Build
菜单,然后按在此处生成<您的项目名称>
,您的控件现在可以在工具箱的顶部找到。现在只需要用你自己的替换每一个正常的 TextBox
。
KeyPress
事件,您可以添加 return;
在 if
-statements中。tbL1Distance
). But I want it as a common textbox control.private void tbL1Distance_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (ch == 46 && tbL1Distance.Text.IndexOf('.') != -1)
{
e.Handled = true;
return;
}
if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
{
e.Handled = true;
}
}
TextBox
, where you override the OnKeyPress
method.public class CustomTextBox : System.Windows.Forms.TextBox
{
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (ch == 46 && this.Text.IndexOf('.') != -1) //Replaced 'tbL1Distance' with 'this' to refer to the current TextBox.
{
e.Handled = true;
}
else if (!Char.IsDigit(ch) && ch != 8 && ch != 46)
{
e.Handled = true;
}
base.OnKeyPress(e);
}
}
Build
menu and press Build <your project name here>
, and your control can now be found on the top of your Tool Box. Now just replace every normal TextBox
with your own.KeyPress
event to be fired at all if your validation fails, you can just add return;
in both if
-statements.