簡體   English   中英

如何更改 RichTextBox 中文本的大小寫?

[英]How do I change the case of text in a RichTextBox?

因此,當在上下文菜單中單擊該選項時,我試圖制作選定數量的文本(在富文本框中) go 大寫或 go 小寫。

這是我嘗試使用的代碼:

private void toUPPERCASEToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (rtxtMain.SelectedText != "")
            {
                rtxtMain.SelectedText.ToUpper();
            }
        }

private void toLowercaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (rtxtMain.SelectedText != "")
            {
                rtxtMain.SelectedText.ToLower();
            }
        }

但是,當我嘗試時,文本沒有改變......我如何改變它?

您無法更改現有的字符串實例。 ToUpper()和ToLower()返回一個新的字符串實例。

嘗試

rtxtMain.SelectedText = rtxtMain.SelectedText.ToUpper();

字符串在C#中是不可變的。 因此,所有內置操作(不僅包括ToLowerToUpper ,還包括ReplaceTrim等)將返回包含修改數據的新字符串。 它們不會更改現有字符串。

這就是為什么,正如其他海報所說,你的答案是

rtxtMain.SelectedText = rtxtMain.SelectedText.ToUpper();
rtxtMain.text =ttxtMain.text.Replace(rtxtmain.SelectedText,rtxtmain.SelectedText.ToUpper())

或者,如果您想以困難的方式做到這一點,這里是另一種選擇。

private void btnCAPS_Click(object sender, EventArgs e)
    {
        int start = rtbTheText.SelectionStart;
        int end = start + rtbTheText.SelectedText.Length;
        string oldValue = rtbTheText.SelectedText;
        string newValue = rtbTheText.SelectedText;
        newValue = newValue.ToUpper();
        string partOne = rtbTheText.Text.Substring(0, (start));
        string partTwo = newValue;
        string partThree = rtbTheText.Text.Substring((end));
        
        string replacement = partOne + partTwo + partThree;
        rtbTheText.Text = replacement;
    }
}

暫無
暫無

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

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