简体   繁体   中英

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

So I'm trying to make a selected amount of text (in a rich text box) go uppercase or go lower case, when that option is clicked in a contextmenu.

Here's the code I'm trying to use:

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

However, when I try it out, the text doesn't change... How do I make it change?

You cannot change an existing string instance. ToUpper() and ToLower() return a new string instance.

Try

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

Strings are immutable in C#. Thus, all the built-in operations, including not only ToLower and ToUpper but also Replace , Trim , etc., will return new strings containing the modified data. They will not change your existing string.

This is the reason why, as the rest of the posters have noted, your answer is

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

Or, alternatively, if you want to do it the hard way, here is the alternative.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM