If we trace the call chain of the Text
1 , 2 , 3 property, we will see the following code:
if (value == null) { value = ""; }
That is, null
cannot be set to this property, anyway, an empty string will be assigned. Therefore, the textBox.Text = null;
method textBox.Text = null;
disappears.
Tracing the call chain of the Clear
method 4 , 5 , we see:
public void Clear() { Text = null; }
Suddenly, the assignment is null
. Hmm, why not immediately assign ""
? ..
In general, use the method, since it is there and calling it a couple of characters shorter.
Modern applications typically use data binding . We do not work directly with graphic controls. Values in them change indirectly.
An example is a cumbersome one, but once I took it upon myself to explain, I’ll finish it.
Suppose we have a class that describes a person who has a name (add other properties yourself). In order for instances of this class to participate in two-way data binding, you need to implement the INotifyPropertyChanged interface.
class Person : INotifyPropertyChanged { private string _name; public string Name { get => _name; set { if (_name != value) { _name = value; NotifyPropertyChanged(); } } } private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public event PropertyChangedEventHandler PropertyChanged; }
Create an instance of this class and bring it to the existing textbox:
var person = new Person { Name = "Bob" }; textBox.DataBindings.Add( nameof(TextBox.Text), person, nameof(Person.Name), false, DataSourceUpdateMode.OnPropertyChanged);
Now to clear the textbox, just clear the bound property:
person.Name = "";
If you create large serious applications, you will inevitably encounter data binding and INotifyPropertyChanged, so you will have to master them.