I want to remove any leading spaces within a TextBox in my windows forms application using .net [closed]
not allowing first character as spaces after textbox allow spaces in windows form application like
textb开发者_如何学编程ox1.text=" fg"; //----------- not like
textbox1.text="vcvc hfh"; //------------Like this
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()
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
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:
- http://www.regular-expressions.info/examples.html
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.
Why not just Trim() the text when you're ready to use it?
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, " ", "");
You could test to see if the key down is the spacebar, or trim it. Perhaps.
精彩评论