Reputation: 329
I've got a textbox that resets back to 0 everytime you delete the last number in the textbox, but what makes this annoying is that when it replaces it; the cursor that you type with moves to the left of the 0, making anything you type afterwards have a 0 after it unless you click after the 0. Is it possible to make it so that when I delete the last digit, it goes back to the right of the newly replaced digit?
private void iterations_TextChanged(object sender, EventArgs e)
{
resetToZero(iterations);
}
private void resetToZero(TextBox x)
{
if (x.Text == "")
{
x.Text = "0";
}
}
Upvotes: 0
Views: 102
Reputation: 37020
To put the cursor at the end of the text, you can just set the SelectionStart
to 1
, which is right after the 0
, or more generically, you can use the length of the text box Text
property:
private void resetToZero(TextBox x)
{
if (x.Text == "")
{
x.Text = "0";
x.SelectionStart = x.TextLength;;
}
}
Or, to put the zero there and then select the text automatically, you can do do:
private void resetToZero(TextBox x)
{
if (x.Text == "")
{
x.Text = "0";
x.SelectionLength = x.TextLength;
}
}
Upvotes: 2
Reputation: 1146
Look into the TextBox.SelectionStart and TextBox.SelectionLength properties.
Upvotes: 2