سؤال

This has always confused me when it comes to Text Boxes on a form. I know that a string can be null or String.Empty, but can a Text Box?

By my understanding, as soon as the control is created it automatically contains "text" (I use inverted commas because while there might not be text in the field, the field exists).

Therefore if a Text box is created, TextBox.Text == null and TextBox.Text == String.Empty are false?

Or is that not true, because TextBox.Text is the same as string?

هل كانت مفيدة؟

المحلول

from TextBox.Text documentation

A string containing the text contents of the text box. The default is an empty string ("").

Therefore if a Text box is created, TextBox.Text is not null, it is String.Empty

You can't set a null value to a control text, the setter of the Text property is implemented as below, As per the implementation null will be convert to empty

  set
  {
    if (value == null)
      value = "";
    if (value == this.Text)
      return;
    .....

نصائح أخرى

I tried:

public partial class MainWindow {
    public MainWindow() {
        InitializeComponent();
        Console.WriteLine("Text is empty:{0}", TextBox1.Text == string.Empty);
        Console.WriteLine("Text is null:{0}", TextBox1.Text == null);
        Console.WriteLine();

        Console.WriteLine("TextBox.Text = null")
        TextBox1.Text = null;
        Console.WriteLine("Text is empty:{0}", TextBox1.Text == string.Empty);
        Console.WriteLine("Text is null:{0}", TextBox1.Text == null);
    }
}

And I got:

Text is empty:True
Text is null:False

TextBox.Text = null
Text is empty:True
Text is null:False

So I guess TextBox.Text converts null into String.Empty.

The TextBox is a class just like any other and it has a property called Text which is of type string.

So the Text property could be null or String.Empty.

You could think of it like this:

 public class TextBox :  Control 
 {
      public string Text {get; set;}
      // other properties ...
 }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow