Introduction
One of the top features of mobile apps is the 'x' button on the Textboxes, making it very easy to clear a textbox form.
In this post, I'll show you how to implement it by sharing a code made by myself. It can be used for all your C# WinForms Apps just by changing the object name.
This works for both .NET Framework and .NET Core 3.0.
Implementation of the Textbox heritage
- using System.Drawing;
- namespace System.Windows.Forms
- {
- public class MyTextBox : TextBox
- {
- private readonly Label lblTheClose;
- public bool ButtonTextClear { get; set; } = true;
- public MyTextBox()
- {
- Resize += PositionX;
- TextChanged += ShowHideX;
- lblTheClose = new Label()
- {
- Location = new Point(100, 0),
- AutoSize = true,
- Text = "x",
- ForeColor = Color.Gray,
- Visible = false,
- Font = new Font("Tahoma", 8.25F),
- Cursor = Cursors.Arrow
- };
- Controls.Add(lblTheClose);
- lblTheClose.Click += (ss, ee) => { ((Label)ss).Visible = false; Text = string.Empty; };
- lblTheClose.BringToFront();
- }
- private void ShowHideX(object sender, EventArgs e) => lblTheClose.Visible = ButtonTextClear && !string.IsNullOrEmpty(Text);
- private void PositionX(object sender, EventArgs e) => lblTheClose.Location = new Point(Width - 15, ((Height - lblTheClose.Height) / 2)-3);
- }
- }
Form Sample
- using System.Drawing;
- namespace System.Windows.Forms
- {
- public partial class Form1 : Form
- {
- /// <summary>
- /// Replace all Textbox by MyTextbox (NO SETUP NEEDED)
- /// </summary>
- private MyTextBox textBox1;
- public Form1()
- {
- InitializeComponent();
- // Just create a Textbox
- textBox1 = new MyTextBox
- {
- Location = new Point(10, 10),
- Size = new Size(300, 20)
- };
- Controls.Add(textBox1);
- // Sample text
- textBox1.Text = "You can clear this field with 'x' button on it.";
- }
- }
- }
How it works:
Using
Now you need to replace your current code
(THIS IS AT YOUR OWN RISK, BE CAREFULLY, TRY-FIRST ON ONLY ONE FORM)
Conclusion
This is a simple implementation but made a big difference for end-users who use mouse or touch screens.
Please remember to like this post and follow me.
Happy coding.

Bruno GasparPosted Sep 12, 2021, 10:37 PM
Hello, thanks for the script! I just have a little problem : when typing it "randomly" hides the X, it appears it painting the teextbox background hover the label. I try to use the BringToFront() on the TextChanged event but without success. If you have some tip let me know. Thank you!