I want to add a "Clear" button on the WinForms ComboBox. So I created a custom control that inherits from ComboBox and added a Label to it. Here's the entire code:
public class ComboBoxClear : ComboBox
{
private readonly Label lblClear;
public ComboBoxClear()
{
lblClear = new Label
{
Location = new Point(0, 0),
AutoSize = true,
Text = "✖",
ForeColor = Color.Gray,
Visible = false,
Font = new Font("Tahoma", Font.Size),
Cursor = Cursors.Hand,
};
Controls.Add(lblClear);
lblClear.Click += (s, e) =>
{
lblClear.Visible = false;
SelectedIndex = -1;
};
lblClear.BringToFront();
SetLocation();
}
[DefaultValue(true)]
[Category("Appearance")]
public bool ShowClearButton { get; set; } = true;
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
lblClear.Visible = ShowClearButton && !string.IsNullOrEmpty(Text);
}
protected override void OnFontChanged(EventArgs e)
{
base.OnFontChanged(e);
lblClear.Font = new Font("Tahoma", Font.Size);
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
SetLocation();
}
private void SetLocation() =>
lblClear.Location = new Point(Width - (lblClear.Width * 2), ((Height - lblClear.Height) / 2) - 3);
}
However, this does not work as expected. When I type, the label shows for a moment then goes hidden if I type again or move the mouse. Interestingly when I hover the mouse over it, the cursor changes but it's like the intersection of the label and the ComboBox is cleared.
I tried overriding the "OnPaint" or handling "Paint" event, none seem to be triggered.