Making a textbox only accept numbers and commas

I want to make a textbox only accept numbers and commas. What is the best way to do this?
bertino12Asked:
Who is Participating?
 
käµfm³d 👽Commented:
My apologies again, I didn't initially see that it was for VB.
Public Class NumberTextBox
    Inherits System.Windows.Forms.TextBox
    Private ReadOnly valids() As Char = {"0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, ","c, ControlChars.Back}
 
    Public Sub New()
        MyBase.New()
    End Sub
 
    Protected Sub NumberTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
 
        If (Not valids.Contains(e.KeyChar)) Then
            e.Handled = True
        End If
    End Sub
 
End Class

Open in new window

0
 
käµfm³d 👽Commented:
You could implement a custom TextBox by inheriting the original and adding some custom code (or just use the custom KeyPress code on your existing box).
class NumberTextBox : System.Windows.Forms.TextBox
{
    private readonly List<char> valids = new List<char>() { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',' };
 
    public NumberTextBox() : base()
    {
        this.KeyPress += new KeyPressEventHandler(NumberTextBox_KeyPress);
    }
 
    void NumberTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!valids.Contains(e.KeyChar))
        {
            e.Handled = true;
        }
    }
}

Open in new window

0
 
käµfm³d 👽Commented:
void NumberTextBox_KeyPress() should be implemented as below. Sorry, I posted incorrect code for that.
void NumberTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if (!valids.Contains(e.KeyChar))
    {
        e.Handled = true;
    }
}

Open in new window

0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
käµfm³d 👽Commented:
If you want backspace to be allowed, then change the char list to the following:
private readonly List<char> valids = new List<char>() { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ',', '\b' };

Open in new window

0
 
Éric MoreauSenior .Net ConsultantCommented:
0
 
bertino12Author Commented:
I get the error:
'Contains' is not a member of 'System.Array'.      
0
 
bertino12Author Commented:
Okay, Just had to change  valids()  to an arraylist so i could use the contains method. Thanks. It seems to be working just fine.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.