限制只在文本框中输入数字?(c#)
本文关键字:数字 输入 文本 | 更新日期: 2023-09-27 18:16:26
请原谅我问这个问题,我已经看过与此相关的各种不同的问题,我仍然不能让它实现。
使用我看过的答案,我收集了这些,并将这些编码应用到我的文本框中。
private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
e.Handled = true;
}
现在,当我继续运行程序时,我仍然可以在里面输入字母。我不知道下一步该做什么,所以任何解决方案都会很棒。谢谢。
好了,这就是我刚才做的,它100%工作刚刚测试过了。注意,我的文本框被命名为serialTxtBox,你可以把它改成你自己的。
void serialTxtBox_TextChanged(object sender, EventArgs e)
{
bool enteredLetter = false;
Queue<char> text = new Queue<char>();
foreach (var ch in this.serialTxtBox.Text)
{
if (char.IsDigit(ch))
{
text.Enqueue(ch);
}
else
{
enteredLetter = true;
}
}
if (enteredLetter)
{
StringBuilder sb = new StringBuilder();
while (text.Count > 0)
{
sb.Append(text.Dequeue());
}
this.serialTxtBox.Text = sb.ToString();
this.serialTxtBox.SelectionStart = this.serialTxtBox.Text.Length;
}
}
编辑:你肯定做错了什么。在以表单命名的表单构造函数中。在我的例子SerialGenerator中,您需要初始化事件。在我的例子中:
public SerialGenerator()
{
InitializeComponent();
this.serialTxtBox.TextChanged += serialTxtBox_TextChanged;
}
this将在每次有人在你的textBox中输入内容时触发该方法。确保将其重命名为文本框的名称
你可以试试:
private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
{
if(!(Char.IsDigit(e.KeyChar) || Char.IsControl(e.KeyChar)))
{ e.Handled = true; }
}
我不认为这是最好的,但是我想你可以稍微调整一下使它工作。我现在没有VS来检查什么是可行的
编辑:我的错。我认为你可以使用上面的一个不是在按键上,而是在文本框的textchanged事件。这更像是一种调整,而不是解决方案。只是为了让你进步,如果你卡住了,没有更好的解决方案。Update:更新代码。
试试这个,希望能成功
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int asciiCode = Convert.ToInt32(e.KeyChar);
if ((asciiCode >= 48 && asciiCode <= 57))
{
}
else
{ MessageBox.Show("Not allowed!");
e.Handled = true;
}
}
我已经在代码级别添加了事件,因为在您的代码中可能存在不正确添加到控件的事件
注意: KeyPress事件不是由非字符键引发的您需要同时使用KeyDown
和KeyPress
事件
public partial class Form1 : Form
{
private bool nonNumberEntered = false;
public Form1()
{
InitializeComponent();
textBox1.KeyDown+=new KeyEventHandler(textBox1_KeyDown);
textBox1.KeyPress+=new KeyPressEventHandler(textBox1_KeyPress);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
e.Handled = true;
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
nonNumberEntered = false;
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
if (e.KeyCode != Keys.Back)
{
nonNumberEntered = true;
}
}
}
if (Control.ModifierKeys == Keys.Shift)
{
nonNumberEntered = true;
}
}
}
REF: Control。KeyPress事件
试试这个…
private void TxtBox5_KeyPress(object sender, KeyPressEventArgs e)
{
int num = 0;
e.Handled = !int.TryParse(e.KeyChar.ToString(), out num);
}