在此字符“。”之后的文本框中 我希望用户只输入 2 个这样的字符
100.00
。我怎样才能做到这一点 ?
5 回答
实现OnTextChanged事件以限制和修改内容
private void textBox1_TextChanged(object sender, EventArgs e)
{
int i = textBox1.Text.IndexOf(".");
if ((i != -1) && (i == textBox1.Text.Length - 4))
{
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
textBox1.SelectionStart = textBox1.Text.Length;
}
}
如果您的目标只是数字,请使用:
winforms http://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown.aspx
wpf WPF 中好的 NumericUpDown 等效项?
asp.net http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/NumericUpDown/NumericUpDown.aspx
您可以在该点之后检查 textbox.text 的长度,以执行此操作。找到'.'的索引 然后如果 textbox.text.length 大于该索引 + 3,则删除最后一个字母。
int indexofDot=textbox.Text.indexOf('.');
if(textbox.text.Length>indexofDot+3) {... }
要删除最后一个字母,只需将字符串复制到另一个临时字符串并删除最后一个字符,然后将其返回到 textbox.Text
您可以使用它的TextChanged
事件来验证输入:
private void textBox1_TextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
double d;
if (!double.TryParse(txt.Text, out d))
{
MessageBox.Show("Please enter a valid number");
return;
}
string num = d.ToString();
string decSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
int numDecPlaces = 0;
int decSepIndex = num.LastIndexOf(decSeparator);
if (decSepIndex != -1)
numDecPlaces = num.Substring(decSepIndex).Length;
if (numDecPlaces > 2)
{
MessageBox.Show("Please enter two decimal places at a maximum");
return;
}
}
首先,您需要确定您是否在功能上想要:
- 防止即通过使用面具,或
- 使用正则表达式验证ie
实施因所选技术而异。
当您选择阻止时,您可以寻找一个MaskedTextBox控件。它在 WinForms 中提供,可以在 WPF 的 Web 上找到。
当您选择验证时,请使用WPF的Windows 窗体的最佳实践。