Friday, May 2, 2008

Escape ampersand (&) character in C#

Problem
Set the Text property of a Label with a string literal having ampersand (&) characters. When the application is run, the ampersand character is not displayed in the label.


The default behaviour of Labels interprets ampersand characters (&) in the Lanel control's Text property as an access key prefix character, and not as a character literal.

Solution
To escape the ampersand character, I will suggest two ways.

1. Use double ampersand. However, this modifies the original string literal, which you probably don't want.


2. Set the Label.UseMnemonic Property to false (since by default, value for the UseMnemonic property is true).


More information on Label.UseMnemonic Property on MSDN

12 comments:

Sunny. said...

Thanks a lot. Informative, succinct, and hard to find elsewhere on the web for those who are less familiar with mnemonics.

Duds said...

Excellent. Ta.

Anonymous said...

Thanks. Just had a problem with this a few minutes ago.

Surya said...

Thanks, you are my saviour

surya said...

Thanks, you are my saviour

smcube said...

Thank you very much

Jai said...

Thanks. Saved my time.

Anonymous said...

Very helpful. Thank you!

Amit said...

thanks a million

Anonymous said...

This post from 2008 has just saved a mere mortal in 2011. And will continue to do so... As-Salamu Alaykum! and Shalom!

Jebaseelan T said...

Thank you

Jebaseelan T said...

Thank you so much