-1

not allowing first character as spaces after textbox allow spaces in windows form application like

       textbox1.text="   fg";  //----------- not like
       textbox1.text="vcvc   hfh"; //------------Like this 
Lloyd Powell
  • 18,270
  • 17
  • 87
  • 123
Ranagababu
  • 7
  • 1
  • 2
  • 3

6 Answers6

5

You could place this code in the TextChanged event or OnKeyDown event (or you could use it whenever you want)

string myString = textBox1.Text.TrimStart()

or even straight to the point

textBox1.Text = textBox1.Text.TrimStart()
Lloyd Powell
  • 18,270
  • 17
  • 87
  • 123
  • I had already mentioned this but the OP didn't like it ..oops he deleted that question ! [See this](http://stackoverflow.com/questions/5987924/validating-textbox-in-windows-form-applications/5988004#5988004) – V4Vendetta May 13 '11 at 08:34
3

This will avoid space at the start of the textbox1

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

Link

Community
  • 1
  • 1
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
1

You could also use a regular expression to remove leading white space by substituting the leading white space with an empty string (""). In this example, " Hello " would become "Hello ":

String result = Regex.Replace(textbox1.text, "^[ \t\r\n]", "");

Similarly, you could strip trailing white space. In this example, " Hello " would become " Hello":

String result = Regex.Replace(textbox1.text, "[ \t\r\n]+$", "");

If you use the pipe operator ( "|" ), you can give both patterns in the same expression to strip both leading and trailing white space. This is the particular one I use in my C# project. It is the .NET equivalent to the Perl chomp command. In this example, " Hello " would become "Hello":

String result = Regex.Replace(textbox1.text, "^[ \t\r\n]+|[ \t\r\n]+$", "");

For a slew of really great tutorial, examples, and reference information on .NET regular expressions, see this site:

Note: To use regular expressions in C#, you must add using System.Text.RegularExpressions; to the top of your C# file.

Note also: If you prefer, you can substitute [ \t\r\n] for the [\s] white space operator.

Steve HHH
  • 12,947
  • 6
  • 68
  • 71
0

To Remove All Space in your Text Even in Start, Middle or End

Here's my Code

using System.Text.RegularExpressions;

txtAfter.Text = Regex.Replace(txtBefore.Text, " ", "");
Christoffer Lette
  • 14,346
  • 7
  • 50
  • 58
0

Why not just Trim() the text when you're ready to use it?

Nathan
  • 6,095
  • 2
  • 35
  • 61
-1

You could test to see if the key down is the spacebar, or trim it. Perhaps.

BugFinder
  • 17,474
  • 4
  • 36
  • 51