user3016556
user3016556

Reputation: 31

Disable white space on key press in textbox

I am beginner in WinForms so i would like to learn that,

How can i disable white space keypress in textbox?

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // MyTextBox.Text ...?
}

Any help will be appreciated.

Upvotes: 3

Views: 17035

Answers (2)

Ceyhun
Ceyhun

Reputation: 1634

that's what you want, disallows all spaces

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

Upvotes: 8

user1968030
user1968030

Reputation:

Use this code:

 private void txt_keyPress(object sender, KeyPressEventArgs e) \
    { 
         if ((sender as TextBox).SelectionStart == 0)
          e.Handled = (e.KeyChar == (char)Keys.Space);
     else
          e.Handled = false; 
    }

Upvotes: 3

Related Questions