-5

I have a ComboBox element in a windows form. It loads a default collection. The user can enter any value manually. How can I prevent the user from entering alphabetical characters?

I want to allow only numeric input, or disable this option altogether.

code4life
  • 15,655
  • 7
  • 50
  • 82
Daniel
  • 1,695
  • 6
  • 23
  • 41
  • See [how to ask a good question](https://stackoverflow.com/help/how-to-ask) – KiwiPiet Aug 09 '17 at 20:53
  • What have you tried? SO is good at helping you break through technical challenges. It's not really set up well to give you tutorials on things, though, because it's more of a Q&A structure. – code4life Aug 10 '17 at 00:05

2 Answers2

1

allow only numbers

In fact, you don't need regex for this simple requirement.

private void comboBox1_TextChanged(object sender, EventArgs e)
{
    if (comboBox1.Text.Any(x => !char.IsDigit(x)))
    {
        comboBox1.Text = string.Concat(comboBox1.Text.Where(char.IsDigit));
        comboBox1.Select(comboBox1.Text.Length, 0);
    }
}

You may also want to add a System.Media.SystemSounds.Beep.Play();

L.B
  • 114,136
  • 19
  • 178
  • 224
-2

You can use Regex As an example In Combobox_TextChanged event if charcter match remove it

 private void comboBox1_TextChanged(object sender, EventArgs e)
 { 
    string rex=comboBox1.Text;
    Regex regex = new Regex(@"^\d$");


    if (regex.IsMatch(compare))
    { 
      rex= Regex.Replace(rex, @"(?<=\d),(?=\d)|[.]+(?=,)[A-Z]", "");
    }
    comboBox1.Text=rex;
  }

This can help you. Regex for numbers only

faikyldrm
  • 68
  • 5