我有以下代码:
private void txtDiscount_TextChanged(object sender, EventArgs e)
{
if (txtDiscount.Text.Equals(""))
{
txtDiscount.Text = "0";
txtDiscount.Select(txtDiscount.Text.Length, 0);
}
Regex regex = new Regex(@"^\d+\.?\d{0,2}$");
if (!regex.IsMatch(txtDiscount.Text))
{
txtDiscount.Text = txtDiscount.Text.Substring(0, txtDiscount.Text.Length - 1);
txtDiscount.Select(txtDiscount.Text.Length, 0);
}
}
private void txtDiscount_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtDiscount.Text.Equals("0"))
{
txtDiscount.Text = e.KeyChar.ToString();
txtDiscount.Select(txtDiscount.Text.Length, 0);
}
}
总而言之,我上面的代码确保用户输入一个数字,而只输入一个数字。可选地,有2个小数位。
如果用户反复点击退格键直到清除所有字符,我希望我的TextBox至少包含一个" 0"。 我的问题是,例如,我的文本框只包含文本" 0"并且用户按下一个键(代表一个数字1到9),我想要" 0"被删除并用按下的数字键替换。
例如: TextBox包含:" 0"。 用户按2。 TextBox现在应该包含" 2",而不是" 02"。 但是,使用上面的代码,我的TextBox显示字符串" 22"代替。它加倍了按下哪个数字键。如果按3,则输出" 33"。
答案 0 :(得分:1)
您可以查看MaskedTextBox
:
MaskedTextBox
类是一个增强的TextBox
控件,支持接受或拒绝用户输入的声明性语法。
我认为这就是你所需要的。
您可以动态更改遮罩以适合特定输入。请参阅此相关答案:dynamically growing masked text- box
答案 1 :(得分:0)
Keypress甚至会自动将按键添加到容器(文本框),以便修复尝试删除
txtDiscount.Text = e.KeyChar.ToString();
答案 2 :(得分:0)
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
var entry = e.KeyChar.ToString();
int output;
if (entry != "\b" && !int.TryParse(entry, out output))
e.Handled = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
var entry = ((TextBox) sender).Text;
if (entry == "0")
((TextBox) sender).Text = "";
}
保持简单。 keyPress在textChanged之前引发。如果用户按下了不需要的键,则使用keyPress处理它。如果用户先按下0,则不接受textChanged。
答案 3 :(得分:0)
只为您的KeyPress
事件处理程序添加一行代码,然后您就可以了:
e.Handled = true;
如果您决定自己处理输入,则需要让Windows Forms知道,否则它将自己处理关键事件(因此过多)。
因此,您的事件处理程序应如下所示:
private void txtDiscount_KeyPress(object sender, KeyPressEventArgs e)
{
if (txtDiscount.Text.Equals("0"))
{
txtDiscount.Text = e.KeyChar.ToString();
txtDiscount.Select(txtDiscount.Text.Length, 0);
e.Handled = true; // <-- add this to your code!
}
}
顺便说一下:当你试图从剪贴板中插入(无效)内容时,你的文本框有点奇怪:它只是在插入符号位置后切断所有字符。
答案 4 :(得分:0)
private void txtDiscount_TextChanged(object sender, EventArgs e)
{
if (txtDiscount.Text.Equals(""))
{
txtDiscount.Text = "0";
txtDiscount.Select(txtDiscount.Text.Length, 0);
}
if (!txtDiscount.Text.Equals("0"))
{
txtDiscount.Text = txtDiscount.Text.TrimStart('0');
txtDiscount.Select(txtDiscount.Text.Length, 0);
}
Regex regex = new Regex(@"^\d+\.?\d{0,2}$");
if (!regex.IsMatch(txtDiscount.Text))
{
txtDiscount.Text = txtDiscount.Text.Substring(0, txtDiscount.Text.Length - 1);
txtDiscount.Select(txtDiscount.Text.Length, 0);
}
}
我遵循了1962年的披头士乐队的建议,谢谢你,先生。对我来说这是一个很大的问题。但是,我认为这几乎解决了我的问题。感谢大家的帮助。