开发者

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

开发者 https://www.devze.com 2023-03-13 23:46 出处:网络
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.

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

精彩评论

暂无评论...
验证码 换一张
取 消