我试图从文本框中删除所选文本并输入新字符代替它.例如,如果文本框由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)
试试这个
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)