Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c# - Validation-Textboxes allowing only decimals

I am using following code for validating 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;  
     }
}

Problem is Constants.vbBack is showing error.If i didnt use Constants.vbBack,backspace is not workimg.What alteration can i make to work backspace.Can anybody help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

here is the code I would use...

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...