gpt4 book ai didi

c# - 允许文本框仅支持数字和 OemMinus?

转载 作者:太空宇宙 更新时间:2023-11-03 16:07:32 28 4
gpt4 key购买 nike

在我的代码中,我使用这段代码来验证仅支持的文本框,但我想允许 OemMinus (-) 我该怎么做?

private void card_No_KeyDown(object sender, KeyEventArgs e)
{
nonNumberEntered = false;

// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9 &&
e.KeyCode == Keys.Oemplus)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}

private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("not allowed");
e.Handled = true;
}
}

最佳答案

你可以像这样处理 KeyPress 事件

private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) && e.KeyChar != '-' && e.KeyChar != (char)Keys.Back)
e.Handled = true;
}

但这不会阻止用户复制粘贴无效值,因此您还可以处理 TextChanged 事件。

private void card_No_TextChanged(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(card_No.Text))
{
if (Regex.Matches(card_No.Text, @"(-|\d)").Count != card_No.Text.Length)
{
//pasted an invalid value
MessageBox.Show("Invalid value entered");
}
}
}

关于c# - 允许文本框仅支持数字和 OemMinus?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18801230/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com