C# 仅允许小数的验证文本框

C# 仅允许小数的验证文本框,c#,winforms,C#,Winforms,我使用以下代码来验证textbox private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = SingleDecimal(sender, e.KeyChar); } public bool SingleDecimal(System.Object sender, char eChar) { string chkstr = "0123456789."; if (chkst

我使用以下代码来验证textbox

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = SingleDecimal(sender, e.KeyChar);
}

public bool SingleDecimal(System.Object sender, char eChar)
{
    string chkstr = "0123456789.";
    if (chkstr.IndexOf(eChar) > -1 || eChar == Constants.vbBack) 
    {
        if (eChar == ".") 
        {
            if (((TextBox)sender).Text.IndexOf(eChar) > -1) 
            {     
                return true;
            }
            else 
            {         
                return false;  
            }
        }   
        return false;
     }
     else 
     {
         return true;  
     }
}

问题是常量。vbBack显示错误。如果我没有使用常量。vbBack,backspace不起作用。我可以对backspace进行什么更改。有人能帮忙吗?

这里是我应用程序中的一些代码。它将处理更多与选择相关的情况

protected override void OnKeyPress(KeyPressEventArgs e)
{
    if (e.KeyChar == '\b')
        return;
    string newStr;
    if (SelectionLength > 0)
        newStr = Text.Remove(SelectionStart, SelectionLength);

    newStr = Text.Insert(SelectionStart, new string(e.KeyChar, 1));
    double v;
   //I used regular expression but you can use following.
    e.Handled = !double.TryParse(newStr,out v);

    base.OnKeyPress(e);
}
这里是正则表达式,如果您想使用它们而不是简单的类型解析

const string SIGNED_FLOAT_KEY_REGX = @"^[+-]?[0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]*)?$";
const string SIGNED_INTEGER_KEY_REGX = @"^[+-]?[0-9]*$";

const string SIGNED_FLOAT_REGX = @"^[+-]?[0-9]*(\.[0-9]+)?([Ee][+-]?[0-9]+)?$";
const string SIGNED_INTEGER_REGX = @"^[+-]?[0-9]+$";

使用来自的示例如何

u是否使用“.”作为小数分隔符?如果是这样,我不知道你为什么要用

if (((TextBox)sender).Text.IndexOf(eChar) > -1)

这是我将使用的代码

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // allows 0-9, backspace, and decimal
    if (((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != 46))
    {
        e.Handled = true;
        return;
    }

    // checks to make sure only 1 decimal is allowed
    if (e.KeyChar == 46)
    {
        if ((sender as TextBox).Text.IndexOf(e.KeyChar) != -1)
            e.Handled = true;
    }
}
private void textBox1\u按键(对象发送器,按键事件参数e)
{
//允许0-9、退格和小数
如果((e.KeyChar<48 | | e.KeyChar>57)和&e.KeyChar!=8和&e.KeyChar!=46))
{
e、 已处理=正确;
返回;
}
//检查以确保只允许1位小数
如果(e.KeyChar==46)
{
if((发送者作为文本框).Text.IndexOf(e.KeyChar)!=-1)
e、 已处理=正确;
}
}

创建从textbox继承的组件并使用以下代码:

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
        {
            e.Handled = true;
        }

        // only allow one decimal point
        if (e.KeyChar == '.' && Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }

        base.OnKeyPress(e);
    }

下面是@Eclipsed4uto的答案的Vb.Net版本

If (((Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57) And Asc(e.KeyChar) <> 8 And Asc(e.KeyChar) <> 46)) Then
    e.Handled = True
    Exit Sub
End If

' checks to make sure only 1 decimal is allowed
If (Asc(e.KeyChar) = 46) Then
    If (sender.Text.IndexOf(e.KeyChar) <> -1) Then
        e.Handled = True
    End If
End If
如果((Asc(e.KeyChar)<48或Asc(e.KeyChar)>57)和Asc(e.KeyChar)8和Asc(e.KeyChar)46))那么
e、 已处理=真
出口接头
如果结束
'检查以确保只允许1位小数
如果(Asc(e.KeyChar)=46),则
如果(sender.Text.IndexOf(e.KeyChar)-1),则
e、 已处理=真
如果结束
如果结束

此代码表示小数。如果还想使用float,只需使用double insteat int 它将自动删除最后一个错误的字符

private void txt_miktar_TextChanged(object sender, TextChangedEventArgs e)
    {
        if ((sender as TextBox).Text.Length < 1)
        {
            return;
        }

        try
        {
            int adet = Convert.ToInt32((sender as TextBox).Text);
        }
        catch
        {
            string s = "";
            s = (sender as TextBox).Text;
            s = s.Substring(0, s.Length - 1);
            (sender as TextBox).Text = s;
            (sender as TextBox).Select(s.Length, s.Length);
        }
    }
private void txt\u miktar\u TextChanged(对象发送方,textchangedventargs e)
{
if((发送者作为文本框)。Text.Length<1)
{
返回;
}
尝试
{
int adet=Convert.ToInt32((发送者作为文本框).Text);
}
抓住
{
字符串s=“”;
s=(发送者作为文本框)。文本;
s=s.子串(0,s.长度-1);
(发件人作为文本框)。Text=s;
(发件人作为文本框)。选择(s.Length,s.Length);
}
}

我认为这是一个完美的解决方案,因为它不仅将文本限制为数字、前导减号和一个小数点,而且允许替换包含小数点的选定文本。如果未选定文本中存在小数点,则选定文本仍不能替换为小数点。仅当它是第一个字符或选中整个文本时,才允许使用减号

private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
{
  if (numeric)
  {
    // only allow numbers
    if (!char.IsDigit(e.KeyChar) && e.KeyChar != Convert.ToChar(Keys.Back))     
      return true;
  }
  else
  {
    // allow a minus sign if it's the first character or the entire text is selected
    if (e.KeyChar == '-' && (txt.Text == "" || txt.SelectedText == txt.Text))
      return false;

    // if a decimal point is entered and if one is not already in the string
    if ((e.KeyChar == '.') && (txt.Text.IndexOf('.') > -1))                     
    {
      if (txt.SelectedText.IndexOf('.') > -1)
        // allow a decimal point if the selected text contains a decimal point, that is the
        // decimal point replaces the selected text 
        return false;
      else
        // don't allow a decimal point if one is already in the string and the selected text
        // doesn't contain one
        return true;                                                        
    }

    // if the entry is not a digit
    if (!Char.IsDigit(e.KeyChar))                                               
    {
      // if it's not a decimal point and it's not a backspace then disallow
      if ((e.KeyChar != '.') && (e.KeyChar != Convert.ToChar(Keys.Back)))     
      {
        return true;
      }
    }
  }

  // allow only a minus sign but only in the beginning, only one decimal point, any digit, a
  // backspace, and replace selected text.
  return false;                                                                   
}

您可以创建一个方法来检查它是否是一个数字

与其将
作为十进制分隔符进行检查,不如从
CurrentCulture
对象中获取它,因为它可能是另一个字符,具体取决于您在世界上的位置

public bool isNumber(char ch, string text)
{
    bool res = true;
    char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

    //check if it´s a decimal separator and if doesn´t already have one in the text string
    if (ch == decimalChar && text.IndexOf(decimalChar) != -1)
    {
        res = false;
        return res;
    }

    //check if it´s a digit, decimal separator and backspace
    if (!Char.IsDigit(ch) && ch != decimalChar && ch != (char)Keys.Back)
        res = false;

    return res;
}
然后,您可以在
文本框的
按键事件中调用该方法:

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(!isNumber(e.KeyChar,TextBox1.Text))
        e.Handled=true;
}

这是一个VB.NET版本,允许负小数,防止复制和粘贴,同时确保否定符号不在文本的中间或小数点不在文本

的开头。 公共子数字(textControl作为对象,e作为KeyPressEventArgs)

Dim索引为Int32=textControl.SelectionStart
将currentLine设置为Int32=textControl.GetLineFromCharIndex(索引)
Dim currentColumn As Int32=索引-textControl.GetFirstCharIndexFromLine(currentLine)
将FullStop变暗为Char
FullStop=“”
Dim Neg As Char
Neg=“-”
'如果按了'.'键,请查看字符串中是否已存在'.'
“如果是这样,不要操作按键
如果e.KeyChar=FullStop和textControl.Text.IndexOf(FullStop)-1,则
e、 已处理=真
返回
如果结束
如果“.”位于数字的开头,请阻止它

如果e.KeyChar=FullStop和currentColumn使用
asp:RegularExpressionValidator
controller尝试此操作

<asp:RegularExpressionValidator ID="rgx" 
ValidationExpression="[0-9]*\.?[0-9][0-9]" ControlToValidate="YourTextBox" runat="server" ForeColor="Red" ErrorMessage="Decimals only!!" Display="Dynamic"  ValidationGroup="lnkSave"></asp:RegularExpressionValidator>

我得到的对象引用未设置为对象的实例。
<asp:RegularExpressionValidator ID="rgx" 
ValidationExpression="[0-9]*\.?[0-9][0-9]" ControlToValidate="YourTextBox" runat="server" ForeColor="Red" ErrorMessage="Decimals only!!" Display="Dynamic"  ValidationGroup="lnkSave"></asp:RegularExpressionValidator>