I am bit confused between the below three ways to clear the contents of a textbox. I am working with WPF and found All are working, but I am unable to find the difference.
Can someone please explain to me about it with some examples?
txtUserName.Clear();
txtUserName.Text = string.Empty;
txtUserName.Text = "";
Just use: TextBox1. Clear() It will work fine.
public void ClearTextBoxes(Form form) { foreach (Control control in form. Controls) { if (control. GetType() == typeof(TextBox)) { control. Text = ""; } } } //Calling this Function var fm1 = new Form1(); ClearTextBoxes(fm1); //Smilarly From Form2 and So on var fm2 = new Form2(); ClearTextBoxes(fm2);
Clear a TextBox With the TextBox. Clear() function is used to clear all the text inside a text box in C#.
If not going really deep:
Clear: remove content from TextBox and may be delete resources allocated with it
public void Clear() { using (this.TextSelectionInternal.DeclareChangeBlock()) { this.TextContainer.DeleteContentInternal(this.TextContainer.Start, this.TextContainer.End); this.TextSelectionInternal.Select(this.TextContainer.Start, this.TextContainer.Start); } }
Assigning empty string (because string.Empty and "" are equal) to Text property just assign empty string to attached property TextBox.TextProperty:
public string Text { get { return (string) this.GetValue(TextBox.TextProperty); } set { this.SetValue(TextBox.TextProperty, (object) value); } }
The Clear()
method does more than just remove the text from the TextBox
. It deletes all content and resets the text selection and caret as @syned's answer nicely shows.
For the txtUserName.Text = "";
example, the Framework will create an empty string
object if one does not already exist in the string pool and set it to the Text
property. However, if the string ""
has been used already in the application, then the Framework will use this value from the pool.
For the txtUserName.Text = string.Empty;
example, the Framework will not create an empty string
object, instead referring to an empty string constant, and set this to the Text
property.
In performance tests, it has been shown (in the In C#, should I use string.Empty or String.Empty or “”? post) that there really is no useful difference between the latter two examples. Calling the Clear()
method is definitely the slowest, but that is clearly because it has other work to do as well as clearing the text. Even so, the difference in performance between the three options is still virtually unnoticeable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With