gunr2171
gunr2171

Reputation: 17579

ListItem.Value overwrites Text if not set

If you set ListItem.Value to a value before setting its Text value, both Text and Value will be set to the same value. I can get around this, but I just want to know why this happens? Is it because something "must" be set to the screen? And why overwrite when the default is an empty string.

.Net 3.5

ListItem li = new ListItem();
li.Value = "abc"; //Text is now = "abc"
li.Text = "def";
li.Value = "qwe"; //Text remains "def"

Upvotes: 6

Views: 1709

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460350

It's because the getter of the Text property is implemented in this way:

get
{
    if (this.text != null)
    {
        return this.text;
    }
    if (this.value != null)
    {
        return this.value;
    }
    return string.Empty;
}

MSDN:

Use the Text property to specify or determine the text displayed in a list control for the item represented by the ListItem. Note If the Text property contains null, the get accessor returns the value of the Value property. If the Value property, in turn, contains null, String.Empty is returned.

The Value property is the other way around:

If the Value property contains null, the get accessor returns the value of the Text property. If the Text property, in turn, contains null, String.Empty is returned.

Upvotes: 7

Related Questions