且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Visual C ++ 2010:只允许TextBox中的数字

更新时间:2023-02-21 12:08:18

有一点调整,我结束了使用Hans Passant建议的方法。

With a little tweak I ended up using the method suggested by Hans Passant.

这是我的最终功能:

private: System::Void tbPDX_KeyPress(System::Object^  sender, System::Windows::Forms::KeyPressEventArgs^  e) {

    if(e->KeyChar == '.'){
        if( this->tbPDX->Text->Contains(".") && !this->tbPDX->SelectedText->Contains(".") )
            e->Handled = true;  
    }
    // Allow negative numbers
    else if(e->KeyChar == '-' && !(this->tbPDX->Text->Contains("-"))){
        e->Handled = true;
        tbPDX->Text = "-" + tbPDX->Text;
    }
    // Accept only digits ".", "-" and the Backspace character
    else if(!Char::IsDigit(e->KeyChar)&& e->KeyChar != 0x08){
        e->Handled = true;
    }
}