I wanted to make a backspace button for my calculator app in windows form the problem is it deletes the character to the right of the cursor, not the left what can I do?
private void DeleteTextValue()
{
//if we don't have any value to delete, return
if (this.UserInput.Text.Length < this.UserInput.SelectionStart + 1)
return;
//remember cursor location
var selectionStart = this.UserInput.SelectionStart;
//delete the char to the right of the cursor
this.UserInput.Text = this.UserInput.Text.Remove(this.UserInput.Text.Length-1, 1);
//restore the cursor location
this.UserInput.SelectionStart = selectionStart;
//unhighlight the text
this.UserInput.SelectionStart = 0 ;
}
Try this, I used substring instead of remove.
private void DeleteTextValue()
{
//if we don't have any value to delete, return
if (this.UserInput.Text.Length < this.UserInput.SelectionStart + 1)
return;
//remember cursor location
var selectionStart = this.UserInput.SelectionStart;
//delete the char to the right of the cursor
//this.UserInput.Text = this.UserInput.Text.Remove(this.UserInput.Text.Length - 1, 1);
if (UserInput.SelectedText.Length > 0)
{
UserInput.Text = this.UserInput.Text.Substring(0, this.UserInput.SelectionStart) + "" + this.UserInput.Text.Substring(this.UserInput.SelectionStart + this.UserInput.SelectionLength);
selectionStart = selectionStart - this.UserInput.SelectionLength;
}
else
{
UserInput.Text = this.UserInput.Text.Substring(0, this.UserInput.SelectionStart - 1) + "" + this.UserInput.Text.Substring(this.UserInput.SelectionStart);
selectionStart = selectionStart - 1;
}
UserInput.Focus();
//restore the cursor location
this.UserInput.SelectionStart = selectionStart;
//unhighlight the text
this.UserInput.SelectionLength= 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.