validating textbox in windows form application

牧云@^-^@ 提交于 2019-12-29 08:14:30

问题


how to validate the textbox without allowing spaces in windows form application using C#.net in my project .i can validate the text box ,without allowing spaces.... in this two things ............. 1.only spaces are not allowed 2.after entering one or two characters textbox accept spaces...........


回答1:


You can restrict the user from entering space in the TextBox by handling the KeyPress event

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = (e.KeyChar == (char)Keys.Space);
}

EDIT

In case space is allowed after entering a character or two , then you should be using

textbox1.Text.TrimStart()




回答2:


It depends on what you mean by "validate". Winforms has the Validating and Validate events that fire when you leave a control. You could tap into these and validate your textbox then. However, if you want to validate as you type, you want to use the Key_Press event to check every time a key is pressed to be sure the information in the box is still valid.

Here is a SO article on validation:

WinForm UI Validation

The answers in there give some different ideas depending on what you want to do. Whatever you decide, be sure to make sure you check the field properly. For example, if you use Key_Press, don't just count how many characters are in the field before allowing a space. If you did that, the user could have moved the cursor to the beginning and pressed space. That would mess up your system. Make sure to check the entire field when you validate, even if you are using the Key_Press event. Use RegEx with as complex a pattern as you want to do this.




回答3:


If you don't want to allow any other characters entry except for the alphanumeric characters in a TextBox, then you can do this on the KeyPress event of a TextBox.

In the KeyPress Event, you need to check whether the entered character is either a Letter or a Digit.

Char.IsLetterOrDigit(e.KeyChar)

If yes, then allow the Key pressing by setting

"e.Handled = false"

Otherwise, don't allow the Key pressing by setting "e.Handled = true"

    private void txtCardID_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsLetterOrDigit(e.KeyChar)     // Allowing only any letter OR Digit
        || e.KeyChar == '\b')                 // Allowing BackSpace character
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }


来源:https://stackoverflow.com/questions/5987286/validating-textbox-in-windows-form-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!