Search code examples
c#treeview

How To Show Icon In TreeView Node Using 2 Strings?


If I have a TreeView with the font to Segoa UI Emoji. I need to set a TreeView node icon using 2 strings but doesn't work. Also, what value can I use for the unicodeEndStr variable below if the unicode only has 4 digits like 2639 ?

// This code shows emoji icon in treeview node followed by a space and some text
string emoji = "\U0001F608" + " " + "Face Savoring Food";
EmojiTreeView.Nodes.Add(emoji);

// This code does not show emoji icon, just \U0001F608 followed by a space and some text
string unicodeStartStr = "\\U000"; // need double back slashes to compile
string unicodeEndStr = "1F608";
string emojiCodeStr = unicodeStartStr + unicodeEndStr;
string emojiStr = emojiCodeStr + " " + "Face Savoring Food";
EmojiTreeView.Nodes.Add(emojiStr); 

Solution

  • First parse your combined Unicode string as hex(16-bit) number. Then use char.ConverFromUtf32(str).ToString() to generate complete Unicode symbol.

    Reference solution: Dynamic generate 8-Digit-Unicode to Character

    public Form1()
    {
               InitializeComponent();
               treeView1.Nodes.Add("\U0001F608" + " " + "Face Savoring Food");
    
               // remove \u prefix
               string unicodeStartStr = "000";  
               string unicodeEndStr = "1F608";
               string emojiCodeStr = unicodeStartStr + unicodeEndStr;
               int value = int.Parse(emojiCodeStr, System.Globalization.NumberStyles.HexNumber);
               string result = char.ConvertFromUtf32(value).ToString();
               string emojiStr = result + " " + "Face Savoring Food";
               treeView1.Nodes.Add(emojiStr);
    }
    

    Worked result