숫자에 대한 텍스트 상자를 마스킹하지만 백 스페이스를 허용하지 않습니다.

StackOverflow https://stackoverflow.com/questions/1060821

  •  21-08-2019
  •  | 
  •  

문제

숫자에 대해서만 원하는 텍스트 상자가 있습니다. 그러나 잘못된 번호를 쳤다면 백 스페이스를 수정할 수 없습니다. 백 스페이스가 작동하도록하는 방법 감사

    private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsNumber(e.KeyChar) != true)
        {
            e.Handled = true;
        }
    }
도움이 되었습니까?

해결책

제어 문자도 허용하기 위해 수표를 추가 할 수 있습니다.

if (Char.IsControl(e.KeyChar) != true && Char.IsNumber(e.KeyChar) != true)
{
    e.Handled = true;
}

업데이트 : 코드에 대한 Person-B의 의견에 대한 응답으로 다음 스타일을 제안합니다 (또한 개인적으로 이것을 작성하는 방법이기도합니다).

if (!Char.IsControl(e.KeyChar) && !Char.IsNumber(e.KeyChar))
{
    e.Handled = true;
}

다른 팁

정답은 다음과 같습니다.

private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !сhar.IsNumber(e.KeyChar) && (e.KeyChar != '\b');
}

TextChanged-Event를 무시할 수도 있습니다.

private void textBox1_TextChanged(object sender, EventArgs e)
{
    string text = (sender as TextBox).Text;

    StringBuilder builder = new StringBuilder(String.Empty);

    foreach (char character in text)
    {
        if (Char.IsDigit(character))
        {
            builder.Append(character);
        }
    }

    (sender as TextBox).Text = builder.ToString();
}

캐럿 위치를 설정하려면 코드를 추가해야합니다.

private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!Char.IsNumber(e.KeyChar) && e.KeyCode != Keys.Back)
          e.Handled = True;
}

위의 약간 더 깨끗한 형식 :

 private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
 {
   e.Handled = !(Char.IsNumber(e.KeyChar) || (e.KeyChar==Keys.Back));
 }

나는 다음이 잘 작동한다는 것을 알았습니다. 백 스페이스, 화살표 키 삭제 키 등을 허용하기위한 추가 예외가 포함되어 있습니다.jQuery를 사용하여 HTML 입력 박스에서 숫자 (0-9) 만 허용하는 방법은 무엇입니까?

private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
    {
        // Allow Digits and BackSpace char
    }        
    else
    {
        e.Handled = true;
    }
}

링크도 참조 : 텍스트 상자를 마스킹하여 소수 만 허용합니다 Decimals/12209854#12209854

주요 프레스 이벤트에서 다음을 사용할 수 있습니다.

      private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsDigit(e.KeyChar) & (e.KeyChar != 8)) e.Handled = true; 
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top