VB.Net .Clear() or txtbox.Text = “” textbox clear methods

旧城冷巷雨未停 提交于 2019-12-08 15:33:43

问题


Not far into programming and just joined this forum of mighty company so this is a silly question, but what is the best way to clear textboxes in VB.Net and what is the difference between the two methods? I have also seen people be critical of folk using clear objects on their forms and I can see why but in this case, I am only learning.

txtbox1.Clear()

or

txtbox1.Text = ""

Any help is much appreciated.


回答1:


The two methods are 100% equivalent.

I’m not sure why Microsoft felt the need to include this extra Clear method but since it’s there, I recommend using it, as it clearly expresses its purpose.




回答2:


The Clear method is defined as

    public void Clear() { 
        Text = null;
    } 

The Text property's setter starts with

        set { 
            if (value == null) { 
                value = "";
            } 

I assume this answers your question.




回答3:


Add this code in the Module :

Public Sub ClearTextBoxes(frm As Form) 

    For Each Control In frm.Controls
        If TypeOf Control Is TextBox Then
            Control.Text = ""     'Clear all text
        End If       
    Next Control

End Sub

Add this code in the Form window to Call the Sub routine:

Private Sub Command1_Click()
    Call ClearTextBoxes(Me)
End Sub



回答4:


Public Sub EmptyTxt(ByVal Frm As Form)
    Dim Ctl As Control
    For Each Ctl In Frm.Controls
        If TypeOf Ctl Is TextBox Then Ctl.Text = ""
        If TypeOf Ctl Is GroupBox Then
            Dim Ctl1 As Control
            For Each Ctl1 In Ctl.Controls
                If TypeOf Ctl1 Is TextBox Then
                    Ctl1.Text = ""
                End If
            Next
        End If
    Next
End Sub

add this code in form and call this function

EmptyTxt(Me)



回答5:


Clear() set the Text property to nothing. So txtbox1.Text = Nothing does the same thing as clear. An empty string (also available through String.Empty) is not a null reference, but has no value of course.




回答6:


Just use:TextBox1.Clear() It will work fine.




回答7:


If u want to Selected text clear then using to this code i will make by my self ;)

If e.KeyCode = Keys.Delete Then
    TextBox1.SelectedText = ""
End If

thats it




回答8:


Specifically if you want to clear your text box in VB.NET or VB 6.0, write this code:

TextBox1.Items.Clear()

If you are using VBA, then the use this code :

TextBox1.Text = "" or TextBox1.Clear()



来源:https://stackoverflow.com/questions/3754108/vb-net-clear-or-txtbox-text-textbox-clear-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!