简体   繁体   English

如何使用当用户进入文本框时,文本消失? C#

[英]How do I make it so that when the user goes into a textbox, the text disappears? C#

Visual C#.NET: Visual C#.NET:

    private void tbAddress_GotFocus()
    {
        tbAddress.Text = "";
    }

    private void tbAddress_LostFocus()
    {
        if (tbAddress.Text == "") { tbAddress.Text = "Email Address"; }
    }

So, I'm trying to use that code to make it so there is text in a (Windows Forms) textbox, and then when the textbox gets focus (when the user clicks inside of it), the text disappears. 所以,我正在尝试使用该代码来使它在(Windows窗体)文本框中有文本,然后当文本框获得焦点时(当用户在其中单击时),文本消失。 That way it looks like a form with the label inside the textbox. 这样,它看起来像一个带有文本框内标签的表单。

So, why doesn't that code work, or is there a better way to do it? 那么,为什么代码不起作用,还是有更好的方法呢?

Use the textBox1.GotFocus event 使用textBox1.GotFocus事件

textBox1.GotFocus += textBox1_GotFocus;//at the designer, constructor or form load...

private void textBox1_GotFocus(object sender, EventArgs e)
{
    textBox1.Clear();//clear the text.
}

//Update: //更新:

If you already did that, then the problem must be in somewhere else, this code should be running without any problem. 如果你已经这样做了,那么问题必须在其他地方,这个代码应该运行没有任何问题。

+1 to @RexM for the pointer to the simplest, and probably best answer. +1到@RexM指向最简单,可能是最佳答案的指针。

There's a more complex approach to this which is loosely based on the idea from this answer . 有一个更复杂的方法,这是基于这个答案的想法松散。 It allows for customizing the color of the displayed text, but it probably has some other problems. 它允许自定义显示文本的颜色,但它可能还有一些其他问题。

I'd really recommend using RexM's answer. 我真的建议使用RexM的答案。 Anyhow, for reference, here's the code for the other approach: 无论如何,作为参考,这是另一种方法的代码:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace MyControls
{
    public class HintedTextBox : TextBox
    {
        public HintedTextBox() : base() { ResetHintColor(); }

        [Description("The color of the hint text to display"),
        Category("Appearance")]
        public Color HintColor { get; set; }
        // Default value handling for HintColor
        private Color DefaultHintColor { get { return Color.LightGray; } }
        public void ResetHintColor() { HintColor = Color.LightGray; }
        public bool ShouldSerializeHintColor() { return !HintColor.Equals(DefaultHintColor); }

        [Description("The textual hint to display in the textbox"),
        Category("Behavior"),
        Localizable(true)]
        public string HintText
        {
            get { return m_hintText; }
            set
            {
                if (m_hintText != value)
                {
                    m_hintText = value;
                    UpdateHintTextState(true);
                }
            }
        }
        private string m_hintText = "";

        protected override void OnGotFocus(EventArgs e)
        {
            base.OnGotFocus(e);
            HasFocus = true;
            UpdateHintTextState();
        }

        protected override void OnLostFocus(EventArgs e)
        {
            base.OnLostFocus(e);
            HasFocus = false;
            UpdateHintTextState();
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            UpdateHintTextState();
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 15) // WM_PAINT
            {
                PaintHintText();
            }
        }

        private bool DisplayHintText { get; set; }

        private bool HasFocus { get; set; }

        private void PaintHintText()
        {
            if (DisplayHintText)
            {
                using (Graphics g = Graphics.FromHwnd(this.Handle))
                using (SolidBrush b = new SolidBrush(HintColor))
                {
                    StringFormat sf = new StringFormat();
                    switch (this.TextAlign)
                    {
                        case HorizontalAlignment.Center:
                            sf.Alignment = StringAlignment.Center;
                            break;
                        case HorizontalAlignment.Right:
                            sf.Alignment = StringAlignment.Far;
                            break;
                        default:
                            sf.Alignment = StringAlignment.Near;
                            break;
                    }
                    g.DrawString(HintText, Font, b, ClientRectangle, sf);
                }
            }
        }

        private void UpdateHintTextState() { UpdateHintTextState(false); }
        private void UpdateHintTextState(bool forceInvalidate)
        {
            bool prevState = DisplayHintText;

            if (HintText.Length == 0)
                DisplayHintText = false;
            else if (Text.Length != 0)
                DisplayHintText = false;
            else
                DisplayHintText = !HasFocus;

            if (DisplayHintText != prevState || forceInvalidate)
                Invalidate();
        }
    }
}

It doesn't work because by default the textbox does not trigger a postback, and without a postback, server side events do not process. 它不起作用,因为默认情况下文本框不会触发回发,如果没有回发,服务器端事件就不会处理。

Your best option here is to use client side javascript to handle this functionality - because round tripping to to the server on each textbox event is wasteful and annoying for the user. 这里你最好的选择是使用客户端javascript来处理这个功能 - 因为在每个文本框事件上向服务器的往返是浪费的并且对用户来说很烦人。

暂无
暂无

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

相关问题 仅当用户在textBox中输入了任何文本才能启用button1时,才如何设置呢? - How do i make that only if the user entered any text to textBox so the button1 will be enabled? 在C#中将文本输入文本框中时,如何使事件发生 - How do you make an event happen when text is entered into a textbox in C# 如何在 Visual Studio C# 中制作一个将特定文本插入文本框中的按钮? - How do i make a button that inserts A Certain text into a textbox in Visual Studio C#? 如何从文本框中获取文本并将其转换为C#中可用的文件路径? - How do I take the text from a textbox and make it into a usable file path in C#? (C# - Forms) 如何从 TextBox.Text 获取用户输入? - (C# - Forms) How do i get user input from TextBox.Text? 如何将用户在文本框中输入的文本移动到C#中的文本块中? - How do I move a text input by user in a textbox, into a textblock in C#? 如何在C#中替换文本框中的部分文本 - how do I replace part of text in textbox in c# 如何在C#Winforms程序的文本框中突出显示文本? - How do I highlight Text in a Textbox in a C# Winforms program? 如何制作 substring 以便在下次出现相同单词时结束(在 C# 中)? - How do I make a substring so that it ends when the next time the same word occurs(in C#)? C# 将文本写入文本框,该文本框将写入的文本添加到链接标签,当点击链接标签时转到 url? - C# write text to textbox which adds written text to linklabel and when linklabel clicked goes to url?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM