I have a custom text box with placeholder effect. If the textbox is empty, the placeholder is shown.
When I pass the value of the textbox (when the textbox is empty and the placeholder is shown instead) to a function , it passes the placeholder value, but I want it to just pass an empty string.
I thought about overriding the Text
property and do an internal check. Something like
public string Text
{
get
{
if (this.Text == this.Placeholder)
{
return "";
}
return this.Text;
}
set
{
this.Text = value;
}
}
but I don't know if this is possible. This would create an infinite loop, I think. How do I make this work?
I know I can use a custom property (e.g., ActualText
instead of Text
) to do this, but if it's possible, I'd like to use Text
. If not, I'll use a custom property.
using System;
using System.Drawing;
using System.Windows.Forms;
using CustomExtensions;
namespace CustomControls
{
public class CustomTextBox : TextBox
{
private string _placeholder;
public string Placeholder
{
get
{
return this._placeholder;
}
set
{
this._placeholder = value;
if (value.IsEmpty(true))
{
this._placeholder = "";
}
else
{
this._placeholder = value;
}
}
}
public CustomTextBox()
{
Initialize();
}
private void Initialize()
{
this.Enter += new EventHandler(this.Placeholder_Hide);
this.Leave += new EventHandler(this.Placeholder_Show);
}
// called from MainForm_Load
public void InitPH()
{
if (!this.Placeholder.IsEmpty(true) && this.Text.IsEmpty())
{
this.Text = this.Placeholder;
this.ForeColor = Color.Gray;
this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
}
}
private void Placeholder_Hide(object sender, EventArgs e)
{
if (this.Text == this._placeholder)
{
this.Text = "";
this.ForeColor = Color.Black;
this.Font = new Font("Segoe UI", 10.2F, FontStyle.Regular);
}
}
private void Placeholder_Show(object sender, EventArgs e)
{
if (this.IsEmpty())
{
this.Text = this._placeholder;
this.ForeColor = Color.Gray;
this.Font = new Font("Segoe UI", 10.2F, FontStyle.Italic);
}
}
public bool IsEmpty()
{
return this.Text.IsEmpty(true, this.Placeholder);
}
}
}