Only allow two digits after decimal in textbox?

后端 未结 7 922
萌比男神i
萌比男神i 2020-12-10 18:54

I have a textbox where the user enters a number, but how can i make it so that if they type the \'.\' after it it only allows 2 decimal places?

private void          


        
7条回答
  •  时光取名叫无心
    2020-12-10 19:41

    To address Casperah's comment above you can change the conditional to handle control characters and allow editing if text is selected.

    if (!char.IsControl(e.KeyChar) 
        && Regex.IsMatch(textBox1.Text, @"\.\d\d")
        && String.IsNullOrWhiteSpace(textBox1.SelectedText))
    {
        e.Handled = true;
    }
    

提交回复
热议问题