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

  1. using System.Drawing;
  2. namespace System.Windows.Forms
  3. {
  4. public class MyTextBox : TextBox
  5. {
  6. private readonly Label lblTheClose;
  7. public bool ButtonTextClear { get; set; } = true;
  8. public MyTextBox()
  9. {
  10. Resize += PositionX;
  11. TextChanged += ShowHideX;
  12. lblTheClose = new Label()
  13. {
  14. Location = new Point(100, 0),
  15. AutoSize = true,
  16. Text = "x",
  17. ForeColor = Color.Gray,
  18. Visible = false,
  19. Font = new Font("Tahoma", 8.25F),
  20. Cursor = Cursors.Arrow
  21. };
  22. Controls.Add(lblTheClose);
  23. lblTheClose.Click += (ss, ee) => { ((Label)ss).Visible = false; Text = string.Empty; };
  24. lblTheClose.BringToFront();
  25. }
  26. private void ShowHideX(object sender, EventArgs e) => lblTheClose.Visible = ButtonTextClear && !string.IsNullOrEmpty(Text);
  27. private void PositionX(object sender, EventArgs e) => lblTheClose.Location = new Point(Width - 15, ((Height - lblTheClose.Height) / 2)-3);
  28. }
  29. }
Form Sample
  1. using System.Drawing;
  2. namespace System.Windows.Forms
  3. {
  4. public partial class Form1 : Form
  5. {
  6. /// <summary>
  7. /// Replace all Textbox by MyTextbox (NO SETUP NEEDED)
  8. /// </summary>
  9. private MyTextBox textBox1;
  10. public Form1()
  11. {
  12. InitializeComponent();
  13. // Just create a Textbox
  14. textBox1 = new MyTextBox
  15. {
  16. Location = new Point(10, 10),
  17. Size = new Size(300, 20)
  18. };
  19. Controls.Add(textBox1);
  20. // Sample text
  21. textBox1.Text = "You can clear this field with 'x' button on it.";
  22. }
  23. }
  24. }
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.