0

I am designing a virtual number pad in Windows Form. Please suppose that I have Del key to remove character of textbox. When I click on the textbox for the first time to select it and then press the Del key, the character is removed correctly relative to cursor position. But after updating the content of text, the SelectionStart property changes to zero and my blinking cursor disappeared. I solved this problem by saving its value temporarily before updating the content of textbox and modifying it at the end.

tempSelectionStart = enteredTextbox.SelectionStart; //save SelectionStart value temporarily 
enteredTextbox.Text = enteredTextbox.Text.Substring(0, enteredTextbox.SelectionStart - 1)
                    + enteredTextbox.Text.Substring(enteredTextbox.SelectionStart,
                      enteredTextbox.Text.Length - (enteredTextbox.SelectionStart));
enteredTextbox.SelectionStart = tempSelectionStart-1;

I want to know:

  1. Is there a more elegant way to solve the problem?
  2. How can I hold cursor blinking in the textbox after first time I pressed the key?

Thanks.

IndustProg
  • 627
  • 1
  • 13
  • 33

1 Answers1

2

Use the SelectedText property instead:

private void DeleteButton_Click(object sender, EventArgs e) {
    if (textBox1.SelectionLength == 0) textBox1.SelectionLength = 1;
    textBox1.SelectedText = "";
    textBox1.Focus();
}

private void BackspaceButton_Click(object sender, EventArgs e) {
    if (textBox1.SelectionLength == 0) {
        if (textBox1.SelectionStart > 0) {
            textBox1.SelectionStart--;
            textBox1.SelectionLength = 1;
        }
    }
    textBox1.SelectedText = "";
    textBox1.Focus();
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536