简体   繁体   中英

Make TextBox text disappear after mouse click

I'm new to C# so this is my first task essentially, I'm hoping to make a simple login page. I would like the text to disappear from the textbox once it has been clicked, here's what I have tried so far;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    bool hasBeenClicked = false;

    private void textBox1_Focus(object sender, EventArgs e)
    {
        TextBox box = sender as TextBox;
        box.Text = string.Empty;
        hasBeenClicked = true;
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }
}

This is from a similar post on here, It doesn't seem to work for me.

Here is something else I have tried;

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

   
    private void textBox1_MouseClick(object sender, MouseEventArgs e)
    {
        textBox1.Text = "";
    }

I understand it may be a silly mistake, I'm learning. Any helps is massively appreciated :) I'm using Winforms

Both of which should probably work but you've got to link the event to the function. You can either do this in the Designer or in code. For the Mouse click variant to work and link the event in code you can add the following in the constructor:

public Form1()
{
    InitializeComponent();
    this.MouseClick += textbox1_MouseClick;
}

Add Event Handler

You have not linked the given methods with the event, as you can see 0 refereces for both functions. You can add a mouse Click event as:

textBox1.Click += new System.EventHandler(textbox1_Mouseclick);

Similarly, you have to add event if you want to do with the focus event.

Try using the event MouseClick on the TextBox:

private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
    this.textBox1.Text = "";
}

In your screenshot, you are missing a reference. Click into the textbox events and add it like so: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM