Amila
Amila

Reputation: 2819

How to format data bound text in a label

I have a label control that is bound to a object collection like

 lblUser.DataBindings.Add(new Binding("Text", UserCollection, "UserName"));

This works fine and the Username on the label. But I need to display the Username as User Name : UserName

How do I add the static "User Name :" part in front of the bound value on the label ?

Upvotes: 0

Views: 2090

Answers (2)

Amila
Amila

Reputation: 2819

The way I did is that I created a custom label by extending the Label class and added an override to the text property. And added this to the text property

set{ Text = "User name :" + value }
get { return value;}

This solved my issue

Upvotes: 0

drharris
drharris

Reputation: 11214

The easiest way is to use two labels, one for the "User Name:" part, and another that contains the bound name. This way you avoid overcomplicating things. In addition, this can help greatly when you're trying to correctly align multiple label values, making your form look better.

If you must use formatting to do it (in particular interest when binding DateTime values), take a look at the Binding.Format event to provide your own format.

Upvotes: 3

Related Questions