c#輸入框設(shè)置默認(rèn)值技巧

c#
小樊
114
2024-07-23 16:25:02

在C#中,可以通過(guò)設(shè)置輸入框的Text屬性來(lái)指定輸入框的默認(rèn)值。以下是一個(gè)簡(jiǎn)單的示例代碼,演示如何設(shè)置輸入框的默認(rèn)值:

using System;
using System.Windows.Forms;

namespace DefaultTextBoxValue
{
    public class MainForm : Form
    {
        private TextBox textBox;

        public MainForm()
        {
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            textBox = new TextBox();
            textBox.Text = "Default Value"; // 設(shè)置默認(rèn)值

            Controls.Add(textBox);
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}

在上面的示例中,我們創(chuàng)建了一個(gè)窗體,并在窗體中添加了一個(gè)文本框。通過(guò)設(shè)置文本框的Text屬性為"Default Value",我們指定了文本框的默認(rèn)值為"Default Value"。當(dāng)用戶(hù)打開(kāi)窗體時(shí),文本框會(huì)顯示這個(gè)默認(rèn)值。

你也可以在需要的時(shí)候清空文本框的內(nèi)容,例如在用戶(hù)單擊文本框時(shí)清空默認(rèn)值。這可以通過(guò)處理文本框的Click事件來(lái)實(shí)現(xiàn)。

0