title: Visual C++ 2010: Only allow numbers in TextBox
body: <p>I'm unfamiliar with Visual Studio, .Net and windows in general, but have been tasked with writing a program that has a windows form. The program pretty much works now, but I have on thing that is bugging me.</p>
  
  <p>I wrote the following function to only allow a number to be input into a <code>TextBox</code>:</p>
  
  <pre><code>private: System::Void tbPDX_KeyPress(System::Object^  sender, System::Windows::Forms::KeyPressEventArgs^  e) {
  
      if(e-&gt;KeyChar == '.'){
          if( this-&gt;tbPDX-&gt;Text-&gt;Contains(".") &amp;&amp; !this-&gt;tbPDX-&gt;SelectedText-&gt;Contains(".") )
              e-&gt;Handled = true;  
      }
      // Allow negative numbers
      else if(e-&gt;KeyChar == '-'){
          if((!System::String::IsNullOrWhiteSpace(this-&gt;tbPDX-&gt;Text)) &amp;&amp; !(this-&gt;tbPDX-&gt;Text-&gt;IndexOf('-') == -1))
              e-&gt;Handled = true;
      }
      // Accept only digits ".", "-" and the Backspace character
      else if(!Char::IsDigit(e-&gt;KeyChar)&amp;&amp; e-&gt;KeyChar != 0x08){
          e-&gt;Handled = true;
      }
  }
  </code></pre>
  
  <p>This works fine for decimal points, but it's not perfect for negatives. For instance I can type <code>0-.0</code>. Is there a way of checking that the position of the character being entered is at the beginning of the <code>String^</code>? From what I can see it's only possible to see the string before the character was entered?</p>