开发者

Restricting textbox input to numbers in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

开发者_如何学C

Closed 8 years ago.

Improve this question

I want to restrict a textbox to accept only numbers in C#. How do I do that?


The most crude down and dirty way of doing it is doing something like this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
    }

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

}

You're still not safe with this approach, as users can still copy and paste non-numeric characters into the textbox. You still need to validate your data regardless.


From others have said before me, we have to almost know what you will use this in, WinForms, ASP.NET, Silverlight ...

But now I take a chance that it is WinForm:)

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
          e.Handled = true;
}


has some bugs but easy way :D

 private void textbox1_TextChanged(object sender, EventArgs e)
        { 
            char[] originalText = textbox1.Text.ToCharArray();
            foreach (char c in originalText)
            {
                if (!(Char.IsNumber(c)))
                {
                    textbox1.Text = textbox1.Text.Remove(textbox1.Text.IndexOf(c));
                    lblError.Visible = true;
                }
                else
                    lblError.Visible = false;
            }
            textbox1.Select(textbox1.Text.Length, 0);
        }


Have you tried the MaskedTextBox control in WinForms?


Have a look at something like this

Masked C# TextBox Control


This may not be the best way, but works ok for WPF TextBox...

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        string originalText = ((TextBox)sender).Text.Trim();
        if (originalText.Length>0)
        {
            int inputOffset = e.Changes.ElementAt(0).Offset;
            char inputChar = originalText.ElementAt(inputOffset);
            if (!char.IsDigit(inputChar))
            {
                ((TextBox)sender).Text = originalText.Remove(inputOffset, 1);
            }
        }
    }


You can use the FilterTextBox of AJAX Control Toolkit. Using this you can allow/disallow any character type. This is quite flexible.


You can use the Microsoft.VisualBasic.Information.IsNumeric is numeric function. Just add the reference Microsoft.VisualBasic

private void textBox1_Validating(object sender,
        System.ComponentModel.CancelEventArgs e) {
    if (!Microsoft.VisualBasic.Information.IsNumeric(textBox1.Text)) {
        e.Cancel = true;
    } else {
        // Do something here
    }
}

This allows the user to enter scientific notation which is not trivial to filter for.


Not sure if this is the correct way, but it works for me, running it on the TextChanged event TextBox has:

    private void CoordinateValidation(object sender, TextChangedEventArgs e) {
        TextBox inputBox = e.OriginalSource as TextBox;
        inputBox.TextChanged -= CoordinateValidation;
        int caretPos = inputBox.CaretIndex;
        foreach (TextChange change in e.Changes) {
            if (inputBox.Text.Substring(change.Offset, change.AddedLength).Any(c => !ValidChars.Contains(c)) ||
                inputBox.Text.Count(c => c == '.') > 1 ||
                (inputBox.Text.Length > 0 && inputBox.Text.Substring(1).Contains('-'))) {
                inputBox.Text = inputBox.Text.Remove(change.Offset, change.AddedLength);
                caretPos -= change.AddedLength;
            }
        }
        inputBox.CaretIndex = caretPos;
        inputBox.TextChanged += CoordinateValidation;
    }


Have a look at the below code

private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        const char Delete = (char)8;
        e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
    }

This will be helpful but users can Copy and Paste characters :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜