如何更改RichTextBox中文本的大小写
本文关键字:大小写 文本 中文 何更改 RichTextBox | 更新日期: 2023-09-27 17:59:22
因此,当在上下文菜单中单击该选项时,我试图使选定的文本量(在富文本框中)变为大写或小写。
这是我尝试使用的代码:
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#中是不可变的。因此,所有内置操作,不仅包括ToLower
和ToUpper
,还包括Replace
、Trim
等,都将返回包含修改数据的新字符串。它们不会更改您现有的字符串。
这就是为什么,正如其他海报所指出的,你的答案是
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;
}
}