从文本框中删除所选文本并在C#.NET中输入新字符

Rus*_*hah 6 c#-4.0

我试图从文本框中删除所选文本并输入新字符代替它.例如,如果文本框由123456和我选择345,并按下r键盘,它应该替换所选文本.

这是我的代码:

string _selectText = txtCal.SelectedText;
string _text = Convert.ToString(btn.Text);

if (_selectText.Length > 0) {
   int SelectionLenght = txtCal.SelectionLength;
   string SelectText = txtCal.Text.Substring(txtCal.SelectionStart, SelectionLenght);
   txtCal.Text = ReplaceMethod(SelectText, _text);
}

//replace method function
public string ReplaceMethod(string replaceString, string replaceText) {
   string newText = txtCal.Text.Replace(replaceString, replaceText);
   return newText;
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我的错误在哪里?

Mat*_*ell 10

如评论中所述,上面提供的基于替换的答案很可能取代错误的选择实例.以下工作取决于职位,并没有遇到这个问题:

textbox1.Text = textbox1.Text.Substring(0, textbox1.SelectionStart) + textbox1.Text.Substring(textbox1.SelectionStart + textbox1.SelectionLength, textbox1.Text.Length - (textbox1.SelectionStart + textbox1.SelectedText.Length));
Run Code Online (Sandbox Code Playgroud)

  • 我认为在第二个子串调用`,textbox1.Text.Length - (textbox1.SelectionStart + textbox1.SelectedText.Length))的末尾添加了许多不必要的代码;`.也许试试这个呢?`textbox1.Text = textbox1.Text.Substring(0,textbox1.SelectionStart)+ textbox1.Text.Substring(textbox1.SelectionStart + textbox1.SelectionLength);` (3认同)

Kun*_*han 1

试试这个

if (textbox1.SelectedText.Length > 0)
{
   textbox1.Text = textbox1.Text.Replace(text1.Text.Substring(textbox1.SelectionStart, textbox1.SelectionLength), btn.Text);                
}
Run Code Online (Sandbox Code Playgroud)