gpt4 book ai didi

c# - 仅输入数字和控制按钮

转载 作者:行者123 更新时间:2023-11-30 21:27:20 26 4
gpt4 key购买 nike

我想输入任意值的 Salary:550,492222,129,3 等等。但是需要像这样使用控制按钮:,, backspace, ctrl + c, ctrl + v, ctrl + a

SalaryTextBoxShortcutsEnabled = true 和事件:

private void TbSalary_KeyPress(object sender, KeyPressEventArgs e)
{
char number = e.KeyChar;
if ((e.KeyChar <= 47 || e.KeyChar >= 58) && number != 8 && number != 44)
//digits, BackSpace and ,
{
e.Handled = true;
}
}

如果删除此条件,指定的组合将起作用。但不仅输入了数字。

我应该在此处添加对所有组合的跟踪吗?或者是否有可能以其他方式实现此任务?

MaskedTextBox 需要固定数量的字符和一些“掩码”。但是 Salary 不同。可以是**,**, ******,* 或者***

更新

防止在小数点后输入两个以上的数字

if (number < ' ')
{
return;
}
if (number >= '0' && number <= '9')
{
if (this.Text.Contains(',')
&& this.SelectionLength == 0
&& this.SelectionStart > this.Text.IndexOf(',')
&& this.Text.Length - this.Text.IndexOf(',') > 2)
{
e.Handled = true;
}

return;
}

最佳答案

请不要使用像 47 这样的魔数(Magic Number),让我们使用字符。我们应该允许这些字符:

  • '0'..'9' 范围(数字)
  • tabbackspace 等控制字符(在空格 ' ' 下方)
  • ','(逗号)作为小数分隔符

所有其他角色都应该被禁止。

代码:

private void TbSalary_KeyPress(object sender, KeyPressEventArgs e)
{
char number = e.KeyChar;
TextBox box = sender as TextBox;

if (number >= '0' && number <= '9' || number < ' ')
return; // numbers as well as backspaces, tabs: business as usual
else if (number == ',') {
// We don't want to allow several commas, right?
int p = box.Text.IndexOf(',');

// So if we have a comma already...
if (p >= 0) {
// ... we don't add another one
e.Handled = true;

// but place caret after the comma position
box.SelectionStart = p + 1;
box.SelectionLength = 0;
}
else if (box.SelectionStart == 0) {
// if we don't have comma and we try to add comma at the 1st position
e.Handled = true;

// let's add it as "0,"
box.Text = "0," + box.Text.Substring(box.SelectionLength);
box.SelectionStart = 2;
}
}
else
e.Handled = true; // all the other characters (like '+', 'p') are banned
}

请注意,有可能粘贴不正确的值(例如,“bla-bla-bla”)到TbSalary 文本框;为了防止它,您可以使用 TextChanged 事件:

private void TbSalary_TextChanged(object sender, EventArgs e) {
TextBox box = sender as TextBox;

StringBuilder sb = new StringBuilder();

bool hasComma = false;

foreach (var c in box.Text)
if (c >= '0' && c <= '9')
sb.Append(c);
else if (c == ',' && !hasComma) {
hasComma = true;

if (sb.Length <= 0) // we don't start from comma
sb.Append('0');

sb.Append(c);
}

string text = sb.ToString();

if (!text.Equals(box.Text))
box.Text = text;
}

关于c# - 仅输入数字和控制按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57887711/

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