11

マイ プログラム:テキストボックスは 1 つだけです。C# 言語を使用してコードを書いています。

私の目的:テキストボックスにテキスト/透かしを表示するには:「あなたの名前を入力してください」。したがって、ユーザーがテキストボックスをクリックすると、デフォルトのテキスト/透かしがクリア/削除され、ユーザーがテキストボックスに自分の名前を入力できるようになります。

私の問題:オンラインで入手できるさまざまなコードを試しましたが、どれもうまくいかないようです。だから、ここで簡単なコードを頼むべきだと思いました。オンラインでコードを見つけましたが、うまくいかないようです:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SetWatermark("Enter a text here...");
        }

        private void SetWatermark(string watermark)
        {
            textBox1.Watermark = watermark;
        }
    }
}

エラー:

エラー 1 'System.Windows.Forms.TextBox' には 'Watermark' の定義が含まれておらず、タイプ 'System.Windows.Forms.TextBox' の最初の引数を受け入れる拡張メソッド 'Watermark' が見つかりませんでした (ディレクティブまたはアセンブリ参照を使用していますか?)

私が目指しているものについて他に何か提案があれば、よろしくお願いします。オンラインで多くの例に飽きましたが、すべてがわかりにくい/機能しません。事前にご協力いただきありがとうございます。:)

4

1 に答える 1

36

これを試してみました。新しい Windows Forms プロジェクトでは問題なく動作するようです。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        textBox1.ForeColor = SystemColors.GrayText;
        textBox1.Text = "Please Enter Your Name";
        this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave);
        this.textBox1.Enter += new System.EventHandler(this.textBox1_Enter);
    }

    private void textBox1_Leave(object sender, EventArgs e)
    {
        if (textBox1.Text.Length == 0)
        {
            textBox1.Text = "Please Enter Your Name";
            textBox1.ForeColor = SystemColors.GrayText;
        }
    }

    private void textBox1_Enter(object sender, EventArgs e)
    {
        if (textBox1.Text == "Please Enter Your Name")
        {
            textBox1.Text = "";
            textBox1.ForeColor = SystemColors.WindowText;
        }
    }
}
于 2013-08-28T20:13:54.393 に答える