问题描述
我开发了一个计算器,但问题是它需要从文本框输入,文本框(当然)除了任何类型的字符.....我怎么能将它们限制为仅限数字,以便当用户按下时除了数字之外的任何按钮都没有写......
i尝试在textbox textchanged事件处理程序中写这个.....
if(txt1.text ==0|| txt1.text ==1|| txt1.text ==2|| txt1.text ==3|| txt1.text ==4 || txt1.text == 5 || txt1.text == 6 || txt1.text == 7 || txt1.text == 8 || txt1.text == 9 ){}
else {
txt1.clear
}
这个有效,但在某种程度上只有........唉它只允许一个角色.....根据我的研究我发现按键事件是必需的,但我不知道如何使用它也许你可以解释一下给我一些其他更简单的方法.....提前感谢...
问候,
Ahsan Naveed。
i have developed a calculator but the problem is that it takes input from a textbox and the textbox(of course)excepts any kind of characters.....how can i limit them to numbers only so that when the user presses any button except numbers nothing is written......
i tried writing this in the textbox textchanged event handler.....
if(txt1.text=="0"||txt1.text=="1"||txt1.text=="2"||txt1.text=="3"||txt1.text=="4"||txt1.text=="5"||txt1.text=="6"||txt1.text=="7"||txt1.text=="8"||txt1.text=="9"){}
else{
txt1.clear
}
this works but upto some extent only........alas it allows only one character.....according to my research i have found that keypress event is required but i dont know how to use it perhaps you could explain it to me give me some other easier method.....thanks in advance...
Regards,
Ahsan Naveed.
推荐答案
static HashSet<char> allowedChars = new HashSet<char>() { { '\b', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; // you can add more chars if you want
private void txt1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!allowedChars.Contains(e.KeyChar))
{
e.Handled = true; // setting e.Handled to true cancels the KeyPress event
}
}
希望这会有所帮助。
数组已更改为 HashSet
并将其设为 static
,如PIEBALDconsult建议[/ Edit]
Hope this helps.
Array changed into HashSet
and made it static
, as PIEBALDconsult suggested[/Edit]
这篇关于如何只允许在文本框中输入某些字符。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!