112

How would one enter special characters into a Label in C# (Windows Forms)?

If you try to write a "&" into a label you'll get a sort of underscore instead..

So what's the C# equivalent of "&"? ("\&" obviously doesn't work).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Spectraljump
  • 4,189
  • 10
  • 40
  • 55

5 Answers5

226

Two ways:

  • Escape it with another ampersand (&&).

  • Set UseMnemonic for that label to false. This causes all ampersands within the text to be taken literally so you don't need to double any of them. You'll lose the underlining and access key features though.

    You can set the value either in the designer, or in code:

    myLabel.UseMnemonic = false;
    myLabel.Text = "Text&Text";
    
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 3
    I already knew (and used) the `&&` pattern but the `UseMnemonic` i never saw before. So +1 for this new enlightening. – Oliver Dec 01 '10 at 14:17
  • 3
    This is the canonical answer. Duplicates to this question includes http://stackoverflow.com/questions/4324310, http://stackoverflow.com/questions/7737532, http://stackoverflow.com/questions/9100607 and http://stackoverflow.com/questions/4324310. – Peter Mortensen Jun 15 '12 at 08:38
  • 1
    Since `ToolStripStatusLabel` doesn't have this property, if I want to use this on a StatusStrip am I forced to escape it with another ampersand? – AdamMc331 Sep 21 '15 at 15:19
  • 2
    @McAdam331: I believe so. – BoltClock Sep 21 '15 at 15:40
  • 1
    @BoltClock thanks. It was easy enough to do, I just used `String.Replace("&", "&&")` whenever I set the text, so I could escape the ampersand without mutating my object itself and screw up how it's displayed elsewhere. – AdamMc331 Sep 21 '15 at 15:45
  • In Delphi, the `UseMnemonic` equivalent is `ShowAccelChar`. – AlainD Jan 16 '19 at 15:48
20

Add another ampersand in front of it, so: &&

Or have a look at the following: Label.UseMnemonic (MSDN documentation)

Jens
  • 3,249
  • 2
  • 25
  • 42
9

You can escape & by adding it two times, to try &&.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
0

I don't know how to use '&' in the designer, but in the code you can use '&&' for showing one '&'

basti
  • 2,649
  • 3
  • 31
  • 46
-4

Try this:

((char)0x26).ToString()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131