[英]textbox text remove last character
If the string is > 8, I need to remove the last character 如果字符串> 8,则需要删除最后一个字符
How is this possible? 这怎么可能?
private void textBoxNewPassword_TextChanged(object sender, EventArgs e)
{
if (textBoxNewPassword.TextLength == 9)
textBoxNewPassword.Text = textBoxNewPassword.Text.Remove((textBoxNewPassword.Text.Length - 1), 1);
}
The code appears to do nothing. 该代码似乎无能为力。
Take an 8-character substring: 取一个8个字符的子字符串:
textBoxNewPassword.Text = textBoxNewPassword.Text.Substring(0, 8);
Better yet, set the MaxLength
property on your TextBox
to 8. 更好的是,将
TextBox
的MaxLength
属性设置为8。
Use String.Substring Method (Int32, Int32) , where the first parameter is the starting index and 2nd parameter is the number of characters. 使用String.Substring方法(Int32,Int32) ,其中第一个参数是起始索引,第二个参数是字符数。 Also if you need to check if the length is greater than 8 the do:
另外,如果您需要检查长度是否大于8,请执行以下操作:
if (textBoxNewPassword.Text.Length > 8)
textBoxNewPassword.Text = textBoxNewPassword.Text.SubString(0,8);
The spirit of your usage of Remove()
is not improper, but you are forgetting that the first argument of Remove(int, int)
is zero-based . 使用
Remove()
的精神并不恰当,但是您忘记了Remove(int, int)
的第一个参数是从零开始的 。 Therefore, when you establish that in your if
statement that the length is 9 ( TextBoxBase.TextLength
simply overlays TextBoxBase.String.Length
in most - but not all - cases), you are addressing the last character in your string when you Remove
at position 8. Your code would have worked if you used instead: 因此,当您在
if
语句中确定长度为9时( TextBoxBase.TextLength
在大多数(但不是全部)情况下仅覆盖TextBoxBase.String.Length
),当您在“位置”处Remove
时,您正在寻址字符串中的最后一个字符8.如果您改用以下代码,则该代码将有效:
textBoxNewPassword.Text = textBoxNewPassword.Text.Remove((textBoxNewPassword.Text.Length - 2), 1);
But I think everyone can agree that the Substring
solution is cleaner and less brittle. 但是我认为每个人都可以同意
Substring
解决方案更干净,更不易碎。 I only mention this so we can understand why it was apparently doing nothing in the first place. 我只提到这一点,因此我们可以理解为什么它一开始似乎什么都不做。
To do exactly as your question asks 完全按照您的问题要求
private void textBoxNewPassword_TextChanged(object sender, EventArgs e)
{
if (textBoxNewPassword.Text.Length > 8)
{
textBoxNewPassword.Text = textBoxNewPassword.Text.Substring(0, textBoxNewPassword.Text.Length - 1);
}
}
You said you only wanted to remove the last character if it's over a 8 characters long. 您说过,您只想删除最后一个超过8个字符的字符。
This is a possible generic solution. 这是一种可能的通用解决方案。
static void Main(string[] args)
{
string text = "The max length is seven".RemoveChars(7);
}
public static string RemoveChars(this string text, int length)
{
if (!String.IsNullOrEmpty(text) && text.Length > length)
text = text.Remove(length, text.Length - length);
return text;
}
Hope this help. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.