更新时间:2023-02-21 12:22:09
使用它:
http://***.com/questions/463299/how-do-i-make-a-textbox-that -only-accepted-numbers [ ^ ]
而不是TextChanged
事件,请使用KeyPress
事件,并尝试以下代码:
Instead of theTextChanged
event, use theKeyPress
event, and try this code:
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]
hi,men!
使用Regex类,你可以这样做。
men!
use the Regex class ,you can do that .