Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Selected Text from Textbox and Enter New Char in C#.NET

Tags:

c#-4.0

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?

like image 239
Rushabh Shah Avatar asked Sep 11 '12 18:09

Rushabh Shah


2 Answers

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));
like image 64
Matt Burnell Avatar answered Nov 19 '22 14:11

Matt Burnell


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;
like image 2
John Kurtz Avatar answered Nov 19 '22 13:11

John Kurtz