I searched on the Internet how to make a placeholder for TextBox but did not find a compact code and decided to invent another bicycle.

The form has a textbox in the properties is Text = "Placeholder Text" and Tag = "Placeholder Text", then I hang up an event handler

Determine the colors of the placeholder

Color LeaveColor = Color.FromArgb(160, 160, 160); Color EnterColor = Color.FromArgb(0, 0, 0); private void txt_kontrIn_Leave(object sender, EventArgs e) { if(txt_kontrIn.Text == "") { txt_kontrIn.Text = (string)txt_kontrIn.Tag; txt_kontrIn.ForeColor = LeaveColor; } } 

and

 private void txt_kontrIn_Enter(object sender, EventArgs e) { if(txt_kontrIn.Text == (string)txt_kontrIn.Tag) { txt_kontrIn.Text = ""; txt_kontrIn.ForeColor = EnterColor; } } 

How true is this solution and can this code still be shortened?

Ps on the form a lot of textboxes.

  • If the user enters "Placeholder Text", then the text will disappear =) - Raider
  • @Raider will not enter =) For each textbox, your text will be - Artneo
  • Are they readonly? - Raider
  • @Raider is not, most of the data the user will choose from the tips - Artneo
  • @Raider on the form of the order of 20 textboxes and for each enter the value of something not very eager - Artneo

1 answer 1

on the form a lot of textboxes.

Make a class-successor textbox that will add placeholder. Use it.

How true is this solution

It is better to keep a separate flag, whether the field is empty. If empty, then replace as now, if not, then do not touch. This will allow the user to enter text that matches the placeholder.

Is it possible to shorten this code?

Stop copying the code and make a class that encapsulates the appropriate logic.