ASP.NET: Bind a Name/Value Pair to a label


Every once in a while, I have a need to bind a label but be able to pull the value back separate from caption/text. In WebForms we can use the Attribute field to accomplish this. In simple example, I’m just going to set the label’s values equal to a name and an associated id:

Label1.Text = "Blake"
Label1.Attributes("PersonId") = 1473

One thing to note, you will not want your Attribute’s name to overlap with that of an actual HTML element name for the standard you’re using (e.g., don’t use “id”, “style”, “width”, etc.. These obviously have special meaning and you will probably end up with undesirable consequences as a result.

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.