How do I fill an empty textbox with default text?

后端 未结 6 1760
独厮守ぢ
独厮守ぢ 2020-12-01 08:55

How do I fill a textbox with text if it is empty? I am using VB.NET.

6条回答
  •  天涯浪人
    2020-12-01 09:04

    You will probably want to handle the TextChanged event and set some default text if the text box is empty when the event is fired.

    I don't have a VB.NET example, but the following C# should be too hard to understand:

    public Form1()
    {
        this.InitializeComponent();
    
        textBox1.Tag = "Default text";
        textBox1.Text = (string)textBox1.Tag;
        textBox1.TextChanged += new EventHandler(OnTextChanged);
    }
    
    void OnTextChanged(object sender, EventArgs e)
    {
        var textbox = (TextBox)sender;
    
        if (string.IsNullOrEmpty(textbox.Text))
        {
            textbox.Text = (string)textbox.Tag;
        }
    }
    

    And the event handler can be reused for several text boxes.

    EDIT: Here's pretty much the same in VB.NET

    Sub New()
        ' This call is required by the designer.
        InitializeComponent()
    
        TextBox1.Tag = "Default text"  ' This can be set with the designer
        TextBox1.Text = CStr(TextBox1.Tag)
    End Sub
    
    Private Sub OnTextBoxTextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Dim textbox As TextBox = DirectCast(sender, TextBox)
    
        If String.IsNullOrEmpty(textbox.Text) Then
            textbox.Text = CStr(textbox.Tag)
            textbox.SelectAll()
        End If
    End Sub
    

    Of course, you can also achieve similar behavior using native Windows functionality, but a few lines of managed code will give you pretty much all you need even if you do not want to use Win32.

提交回复
热议问题