Setting cursor at string position within textbox

Asked

Viewed 268 times

-1

I’m trying to make a mask for a textbox manually, and I’m trying to imitate the Windows calculator, where when the user writes 1000 the code automatically puts 1.000 and when I give one txtPreco.Text = the course is at the beginning of the string |1.000. I want to place the cursor at the end of the string 1.000| but I don’t know which method or event does it.

  • Show the code of how you are doing

  • https://1drv.ms/u/s! Ah1rfu-Nxwbqgaqh6g4gnilcbtr8qq

  • You must edit the question and put the code directly into it - as link may become inaccessible in the future, for other people reading the question

1 answer

0


To keep the cursor at the end of the content you must use the properties SelectionStart and SelectionLength of TextBox.

See the example below:

private void txtPreco_KeyUp(object sender, KeyEventArgs e)
{
    if (!string.IsNullOrWhiteSpace(txtPreco.Text))
    {
        var valor = Int64.Parse(txtPreco.Text,                                
                           System.Globalization.NumberStyles.AllowThousands);


        txtPreco.Text = string.Format(new System.Globalization.CultureInfo("pt-BR")
                                      "{0:N0}", valor);

        txtPreco.SelectionStart = txtPreco.Text.Length;
        txtPreco.SelectionLength = 0;
    }

}

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.