简体   繁体   中英

How to set the insertion point at the first line of textbox?

How to set the insertion point at the first line of text box when I press enter if null value?

I used

if (e.KeyChar == (char)Keys.Enter)
{
    //some text
    textBox1.Text = "";
    textBox1.Focus();
}

Nothing happens though.

Reason for failure: you are assigning Empty String into TextBox instead of Comparing

Solution : You need to check for Empty String using if Condition.

Try This:

if (e.KeyChar == (char)Keys.Enter)
{    
    //some text
    if(textBox1.Text.Trim().Equals(""))
        textBox1.Focus();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {

        if (e.KeyChar == (char)Keys.Enter)
        {
            e.Handled = true;
            if (textBox1.Text.Trim() == "")
                {
                MessageBox.Show("Empty");
                textBox1.Focus();
                 }
           else 
           textBox2.Focus();

        }
    }
if(e.KeyChar == (char)Keys.Enter)
{
   if(string.IsNullOrEmpty(textBox1.Text))    
      textBox1.Focus();
   else
      textBox1.Text = string.Empty;
}

Make it simple and useful

if (e.KeyChar == (char)Keys.Enter)
{

    textBox1.Text = "";
    textBox1.SelectionStart = 1;

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM