I am trying to delete selected text from textbox and enter new character in place of it.
For example, if textbox consists of 123456
and I select 345
, and press r on the keyboard, it should replace the selected text.
here is my code:
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;
}
Can anyone show me where my mistake is?
The replace-based answer offered above may well replace the wrong instance of the selection, as noted in the comments. The following works off positions instead, and doesn't suffer that problem:
textbox1.Text = textbox1.Text.Substring(0, textbox1.SelectionStart) + textbox1.Text.Substring(textbox1.SelectionStart + textbox1.SelectionLength, textbox1.Text.Length - (textbox1.SelectionStart + textbox1.SelectedText.Length));
The following does what you want and then selects the replacing text :)
string _text = Convert.ToString(btn.Text);
int iSelectionStart = txtCal.SelectionStart;
string sBefore = txtCal.Text.Substring(0, iSelectionStart);
string sAfter = txtCal.Text.Substring(iSelectionStart + txtCal.SelectionLength);
txtCal.Text = sBefore + _text + sAfter;
txtCal.SelectionStart = iSelectionStart;
txtCal.SelectionLength = _text.Length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With