2012-04-06 3 views
-1

십진수 값을 가져 오는 텍스트 상자가 있습니다. 10500.00 문제는 값을 입력 한 다음 십진법을 입력하면 백 스페이스 또는 텍스트 상자를 지우지 못하게하는 것입니다. 새로운 값을 입력 .. 그냥 막혔어요. 내가 다시 0.00으로 값을 설정하려고했지만 내가 그것을 바꿀 수 없기 때문에 내가 잘못된 장소에 배치 생각합니다. 여기십진수 입력 기능이있는 텍스트 상자

private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e) 
     { 
      bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), @"\.\d\d"); 
      if (matchString) 
      { 
       e.Handled = true; 
      } 

      if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
      { 
       e.Handled = true; 
      } 

      // only allow one decimal point 
      if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
      { 
       e.Handled = true; 
      } 
     } 

변화의 어떤 종류의 당신은 내가 백 스페이스 또는 texbox을 취소하는 A 새 값을 입력 할 수있을 정도로 되죠 내 코드?

답변

1

는 발견하는 경우, 거짓으로 핸들을 설정합니다.

귀하의 코드는 다음과 같이 보일 수 있습니다 ...

.... 
// only allow one decimal point 
if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
{ 
    e.Handled = true; 
} 

if (e.KeyChar == (char)8) 
    e.Handled = false; 

제안이 당신의 코드를 좀 더 직관적 인 이벤트 핸들러가 무엇을하고 있는지 해석 할 수 있도록, 당신은 논리를 암시 VAR을 만들 수 있습니다 당신은 구현 중입니다. 뭔가가 ...

private void txtTransferAmount_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    bool ignoreKeyPress = false; 

    bool matchString = Regex.IsMatch(textBoxTransfer.Text.ToString(), @"\.\d\d"); 

    if (e.KeyChar == '\b') // Always allow a Backspace 
     ignoreKeyPress = false; 
    else if (matchString) 
     ignoreKeyPress = true; 
    else if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
     ignoreKeyPress = true; 
    else if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
     ignoreKeyPress = true;    

    e.Handled = ignoreKeyPress; 
} 
1

가장 쉬운 방법은 다음과 같습니다

당신은 백 스페이스 (BS) CHAR (8) 트랩 할 수 및
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.' && e.KeyChar != '\b') 
{ 
    e.Handled = true; 
} 
관련 문제