簡體   English   中英

文本框文字刪除最后一個字符

[英]textbox text remove last character

如果字符串> 8,則需要刪除最后一個字符

這怎么可能?

private void textBoxNewPassword_TextChanged(object sender, EventArgs e)
{
    if (textBoxNewPassword.TextLength == 9)
        textBoxNewPassword.Text = textBoxNewPassword.Text.Remove((textBoxNewPassword.Text.Length - 1), 1);
}

該代碼似乎無能為力。

取一個8個字符的子字符串:

textBoxNewPassword.Text = textBoxNewPassword.Text.Substring(0, 8);

更好的是,將TextBoxMaxLength屬性設置為8。

使用String.Substring方法(Int32,Int32) ,其中第一個參數是起始索引,第二個參數是字符數。 另外,如果您需要檢查長度是否大於8,請執行以下操作:

if (textBoxNewPassword.Text.Length > 8)
    textBoxNewPassword.Text = textBoxNewPassword.Text.SubString(0,8);

使用Remove()的精神並不恰當,但是您忘記了Remove(int, int)的第一個參數是從零開始的 因此,當您在if語句中確定長度為9時( TextBoxBase.TextLength在大多數(但不是全部)情況下僅覆蓋TextBoxBase.String.Length ),當您在“位置”處Remove時,您正在尋址字符串中的最后一個字符8.如果您改用以下代碼,則該代碼將有效:

textBoxNewPassword.Text = textBoxNewPassword.Text.Remove((textBoxNewPassword.Text.Length - 2), 1);

但是我認為每個人都可以同意Substring解決方案更干凈,更不易碎。 我只提到這一點,因此我們可以理解為什么它一開始似乎什么都不做。

完全按照您的問題要求

    private void textBoxNewPassword_TextChanged(object sender, EventArgs e)
    {
        if (textBoxNewPassword.Text.Length > 8)
        {
            textBoxNewPassword.Text = textBoxNewPassword.Text.Substring(0, textBoxNewPassword.Text.Length - 1);
        }
    }

您說過,您只想刪除最后一個超過8個字符的字符。

這是一種可能的通用解決方案。

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;
    }

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM