I'm trying to create a simple textbox that shows a hint text when it's not focused and its text is empty, and hides the hint text when it's focused. To do that, I created a Custom Control by extending TextBox.
public partial class HintedTextBox : TextBox
{
private Color foreColor;
public HintedTextBox()
{
InitializeComponent();
foreColor = ForeColor;
GotFocus += OnFocused;
LostFocus += OnFocusLost;
OnFocusLost(null, null); // Problem
}
public string Hint { get; set; }
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
private void OnFocused(object sender, EventArgs e)
{
if (Text == Hint)
{
Text = "";
ForeColor = foreColor;
}
}
private void OnFocusLost(object sender, EventArgs e)
{
if (Text.Trim() == "")
{
Text = Hint;
ForeColor = Color.Gray;
}
else
{
ForeColor = foreColor;
}
}
}
Logically, I would need to call the OnFocusLost() procedure after the component is initialized so the app will show the hint when the Form is first shown. The problem is at the line I marked with // problem. At this line, both my custom attribute Hint and the stock attribute Text are both not initialized, even if I've set their values in the Designer. The weird thing is that the ForeColor attribute is already initialized at that line. Is there another Event that fires as soon as these values are initialized, or is there any other solution?
I've also tried calling OnFocusLost() from outside the Control on Windows Form's FormLoad Event. It doesn't work either. The Text and Hint are just always empty at the start, even after the InitializeComponent() call.
Thank you for your attention.
EDIT:
I forgot to attach the Form's on-load Event to my FormLoad() method, but nonetheless Vladimir Stoyanov's solution worked perfectly and even better.