简体   繁体   English

单击鼠标后使文本框文本消失

[英]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.我是 C# 新手,所以这基本上是我的第一个任务,我希望制作一个简单的登录页面。 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上的类似帖子,它似乎对我不起作用。

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非常感谢任何帮助:) 我正在使用 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.您可以在 Designer 或代码中执行此操作。 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.您尚未将给定方法与事件链接,因为您可以看到这两个函数的引用为 0 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:尝试在 TextBox 上使用事件 MouseClick:

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:单击文本框事件并像这样添加它: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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