Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListItem.Value overwrites Text if not set

Tags:

c#

asp.net

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"
like image 782
gunr2171 Avatar asked Mar 13 '13 21:03

gunr2171


1 Answers

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.

like image 150
Tim Schmelter Avatar answered Oct 23 '22 01:10

Tim Schmelter