简体   繁体   中英

Making TextBox Clear when user starts typing

I have two text boxes in a win forms that the user will be typing information into. I would like to clear the text box when the user start typing. I am using the TextChanged event handler, so every time I type it will erase, which makes me not able to type anything into the text box. Here is the code I am using:

private void TXTBX_HourlyRatae_TextChanged(object sender, EventArgs e)
    {
      TXTBX.HourlyRate.Clear();
      TXTBX.HoursWorked.Clear();
    }

I understand that everytime I type into the text box I will be executing this event handler, but I don't know how to go about making it execute only the first time I type into the text box.

private bool firsttime = true;

private void TXTBX_HourlyRatae_TextChanged(object sender, EventArgs e)
{
      if (firsttime)
      {
          TXTBX.HourlyRate.Clear();
          TXTBX.HoursWorked.Clear();
          firsttime = false;
      }
}

if you want to do it everytime you enter the textbox handle the loss focus event

private void TXTBX_HourlyRatae_LostFocus(object sender, System.EventArgs e)
    {

    }       firsttime = true;

将您的Clear()调用移到相应的EnterGotFocus事件中。

Create a new private class member:

private bool _userHasEnteredText = false;

Only erase the text when this bool is false, then set this bool to true once you've cleared the text the first time.

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