JG Vimalan's Blog

It is all about coding!

Trim the trailing spaces in a textbox using C#.NET

The following code  gives an idea on how to trim the trailing spaces in a textobox when space bar (empty space) is pressed..

  /// <summary>
  /// Occurs after the user presses a key.  Trims the trailing spaces 
  /// </summary>
  /// <param name=”e”></param>
  protected override void OnKeyPress
   (System.Windows.Forms.KeyPressEventArgs e)
  {
    e.Handled = false;
    char ch = e.KeyChar;
    int Position = base.SelectionStart;
    if(ch == ‘ ‘)
    {
      Position = base.SelectionStart;
    if(Position == 0)
    {
       e.Handled = true;
       return;
    }
    
    int Length = base.Text.Length;    
    int EndPosition = Position + SelectionLength;
    if (EndPosition == Length)
    {
     if (base.Text[Position-1] == ‘ ‘)
     {
        e.Handled = true;
     }
     return;
    }
    
    else if ((base.Text[Position-1] == ‘ ‘) ||
     (base.Text[EndPosition] == ‘ ‘))
    {     
       e.Handled = true;
       return;
    }
   }   
  }

Advertisements

October 9, 2009 - Posted by | C#.NET

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: