How To Show Icon In TreeView Node Using 2 Strings? - c#

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);

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

Related

Replace not working when applied to an html string

As an introduction, I have created a document using MS Word and then saved as html document.
From C# I am building an unordered html list (using MS Word format) and then add it to the html document by replacing a specific tag.
I have below string variable unorderedHtmlList initially initialized to empty string. Then I am concatenating html string and replacing some tags enclosed by "[[" and "]]" characters. For some reason when I apply the Replace it is not replacing the items [[fieldName]] and [[fieldValue]] by the new values. See code below:
string unorderedHtmlList = string.Empty;
foreach (System.Data.DataRow row in myDataTable.Rows)
{
string name = row["fieldName"].ToString();
string value = row["fieldValue"].ToString();
unorderedHtmlList += "<p style='margin-left:36.0pt;text-align:justify;text-indent:-18.0pt;" +
"line-height:125%;mso-list:l1 level1 lfo3'><![if !supportLists]><span" +
"style='font-size:10.5pt;line-height:125%;font-family:\"Arial\",sans-serif;" +
"mso-fareast-font-family:Arial;color:#222222'><span" +
"style='mso-list:Ignore'>-<span style='font:7.0pt \"Times New Roman\"'> " +
"</span></span></span><![endif]><span style='font-size:10.5pt;" +
"line-height:125%;font-family:\"Arial\",sans-serif;color:#222222'>[[fieldName]]" +
"</span><span style='font-size:10.5pt;line-height:125%;font-family:" +
"\"Helvetica\",sans-serif;color:#222222'>[[fieldValue]]</span><span" +
"style='font-size:10.5pt;line-height:125%;font-family:\"Arial\",sans-serif;" +
"color:#222222'><o:p></o:p></span></p>".Replace("[[fieldName]]", name).Replace("[[fieldValue]]", value);
}
Any ideas why Replace is not working?
You are concatanating the string and the replace operation is executed only on the last part.
"color:#222222'><o:p></o:p></span></p>".Replace("[[fieldName]]", name).Replace("[[fieldValue]]", value);
Try this:
unorderedHtmlList += ("<p style='margin-left:36.0pt;text-align:justify;text-indent:-18.0pt;" +
"line-height:125%;mso-list:l1 level1 lfo3'><![if !supportLists]><span" +
"style='font-size:10.5pt;line-height:125%;font-family:\"Arial\",sans-serif;" +
"mso-fareast-font-family:Arial;color:#222222'><span" +
"style='mso-list:Ignore'>-<span style='font:7.0pt \"Times New Roman\"'> " +
"</span></span></span><![endif]><span style='font-size:10.5pt;" +
"line-height:125%;font-family:\"Arial\",sans-serif;color:#222222'>[[fieldName]]" +
"</span><span style='font-size:10.5pt;line-height:125%;font-family:" +
"\"Helvetica\",sans-serif;color:#222222'>[[fieldValue]]</span><span" +
"style='font-size:10.5pt;line-height:125%;font-family:\"Arial\",sans-serif;" +
"color:#222222'><o:p></o:p></span></p>").Replace("[[fieldName]]", name).Replace("[[fieldValue]]", value);

Fill Line with hyphens

i'm trying to fill one line of my label with hyphens. Here's what i got right now. what is the function that i can use to fill the next line without manually typing out all the hyphens?
lblResumé.Text = intNbrTotTut.ToString() + str1erePhrase + Environment.NewLine
string myString = "Test" + Environment.NewLine + "Test2" +Environment.NewLine;
label1.Text = myString.Replace(System.Environment.NewLine, "_");

When use String.Insert(int index, string text) insert at the end of the new string: "00000"

I need to insert in a specific position of the string line, another string, so I compute the specific position for start to insert:
string info1 = "info1";
string info2 = "info2";
string info3 = "info3";
string info4 = "info4";
string keyWord = "BELEGIT";
start = line.IndexOf(keyWord, 0) + keyWord.Length + 13;
var aStringBuilder = new StringBuilder(line);
aStringBuilder.Remove(start, 19);
line = aStringBuilder.ToString();
string newLine = line.Insert(start, "\r\n" + info1 + "\r\n" + "\r\n" + info2 + "\r\n" + info3 + "\r\n" + info4 + "\r\n");
(newLine will be the content of a file in my application).
newline contains the correct content except the string "00000" that inserts after "info4". So in my new file with the content that is newline there is newline and immediately after "00000". I do not really understand why.
Thanks in advance.
INPUT:
line contains:
#~11\r\nT-02040121R\r\n\r\n\r\n\r\n\r\n\r\n\n2.000000000\r\n
OUTPUT
newLine contains:
#~11\r\nT-02040121R\r\ninfo1\r\n\r\ninfo2\r\ninfo3\r\ninfo4\r\n00000\r\n
Assuming that you want just the first 19 chars of lineyou could use Substringto get them and string.Formatto build the new string.
Something like this
var start = line.Substring(0, 19);
string newLine = $"{start}\r\n{info1}\r\n\r\n{info2}\r\n{info3}\r\n{info4}\r\n";
The second line is the short form for
string newLine = string.Format("{0}\r\n{1}\r\n\r\n{2}\r\n{3}\r\n{4}\r\n", start, info1, info2, info3, info4);
if you need more information about string.Formathave a look at the MSDN.

Replace closest instance of a word

I have a string like this:
“I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”
I want to insert <strong> around the "a" in "a diplomatic", but nowhere else.
What I have as input is diplomatic from a previous function, and I wan't to add <strong>to the closest instance of "a".
Right now, of course when I use .Replace("a", "<strong>a</strong>"), every single instance of "a" receives the <strong>-treatment, but is there any way to apply this to just to one I want?
Edit
The string and word/char ("a" in the case above) could be anything, as I'm looping through a lot of these, so the solution has to be dynamic.
var stringyourusing = "";
var letter = "";
var regex = new Regex(Regex.Escape(letter));
var newText = regex.Replace(stringyourusing , "<strong>letter</strong>", 1);
Would this suffice?
string MakeStrongBefore(string strong, string before, string s)
{
return s.Replace(strong + " " + subject, "<strong>" + strong + "</strong> " + before);
}
Used like this:
string s = “I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”;
string bolded = MakeStrongBefore("a", "diplomatic", s);
Try this:
public string BoldBeforeString(string source, string bolded,
int boldBeforePosition)
{
string beforeSelected = source.Substring(0, boldBeforePosition).TrimEnd();
int testedWordStartIndex = beforeSelected.LastIndexOf(' ') + 1;
string boldedString;
if (beforeSelected.Substring(testedWordStartIndex).Equals(bolded))
{
boldedString = source.Substring(0, testedWordStartIndex) +
"<strong>" + bolded + "</strong>" +
source.Substring(testedWordStartIndex + bolded.Length);
}
else
{
boldedString = source;
}
return boldedString;
}
string phrase = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
string boldedPhrase = BoldBeforeString(phrase, "a", 41);
Hei!
I've tested this and it works:
String replaced = Regex.Replace(
"I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.",
#"(a) diplomatic",
match => "<strong>" + match.Result("$1") + "</strong>");
So to make it a general function:
public static String StrongReplace(String sentence, String toStrong, String wordAfterStrong)
{
return Regex.Replace(
sentence,
#"("+Regex.Escape(toStrong)+") " + Regex.Escape(wordAfterStrong),
match => "<strong>" + match.Result("$1") + "</strong>");
}
Usage:
String sentence = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
String replaced = StrongReplace(sentence, "a", "diplomatic");
edit:
considering your other comments, this is a function for placing strong tags around each word surrounding the search word:
public static String StrongReplace(String sentence, String word)
{
return Regex.Replace(
sentence,
#"(\w+) " + Regex.Escape(word) + #" (\w+)",
match => "<strong>" + match.Result("$1") + "</strong> " + word + " <strong>" + match.Result("$2") + "</strong>");
}

How to format a string displayed in a MessageBox in C#?

I want to display a string in a message box with a following format:
Machine : TestMachine
User : UserName
I am doing this:
string strMsg = "Machine :" + "TestMahine" + "\r\n" +
"User :" + "UserName";
MessageBox.Show(strMsg);
When I do this the message box do not display a string as formated above. Colon(") dosen't keep alligned. The above format is also do not work in WPF TextBlock control.
Please help!!
Try something like this:
string strMsg = String.Format("Machine\t: {0}\nUser\t: {1}", "TestMachine", "UserName");
Edited: Gotta have that String.Format there or that lone bracket at the end is sad.
The reason for this is that the message box is displayed in a font where Machine and User may not be the same length.
You could try the following:
"Machine\t:" + "TestMahine" + "\r\n" +
"User\t:" + "UserName";
The \t character will probably correctly align your colons.
In a WPF (or WinForms, or Java, or Qt, or whatever) TextBlock, if you want characters to be aligned, you need to use a fixed font length, in order for every character to have the same length than the others.
i.e. Use a font like "Courier New" or "Monospaced" or "Consolas".
In a MessageBox, you cannot control the font-family. If you really want this feature, did you consider creating a customized Window component ? Like this...
<Window x:Class="WpfApplication1.CustomMessageBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
SizeToContent="WidthAndHeight" MaxWidth="500">
<Grid Margin="10">
<TextBlock FontFamily="Courier New" Text="{Binding Message}" />
</Grid>
</Window>
.
public partial class CustomMessageBox : Window, INotifyPropertyChanged {
private string message;
public string Message {
get { return message; }
set { message = value; RaisePropertyChanged("Message"); }
}
public CustomMessageBox() {
InitializeComponent();
DataContext = this;
}
public static void Show(string title, string message) {
var mbox = new CustomMessageBox();
mbox.Title = title;
mbox.Message = message;
mbox.ShowDialog();
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property) {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
As a result, you can invoke your new messagebox with:
string strMsg =
"Machine : " + "TestMahine" + "\r\n" +
"User : " + "UserName";
CustomMessageBox.Show("Hello !", strMsg);
Of course, you will need to do some little arrangements to your custom message box view but you got the idea ;-)
I ran into the same problem trying to align data in a MessageBox and after searching for a while I decided to write my own method using TextRenderer.MeasureText to get measurements at the pixel level. The method takes two parameters; the first is the string to format and the second is the longest string to be shown to the left of the colon (the alignment character in this example).
What the method is doing is prepending blank spaces until the string reaches, but does not exceed, the length of the longest string. The method is called as shown below where "Department: " is the longest string.
StringBuilder sb = new StringBuilder();
string longest = "Department: ";
sb.AppendLine(StringLengthFormat("Result(s): ", longest) + results);
The actual method that does the formatting is:
private string StringLengthFormat(string inString, string longest)
{
Size textSizeMax = TextRenderer.MeasureText(longest, System.Drawing.SystemFonts.DefaultFont);
Size textSizeCurrent = TextRenderer.MeasureText(inString, System.Drawing.SystemFonts.DefaultFont);
do
{
inString = " " + inString;
textSizeCurrent = TextRenderer.MeasureText(inString, System.Drawing.SystemFonts.DefaultFont);
} while (textSizeCurrent.Width < textSizeMax.Width);
return inString;
}
Because I can also have one or more lines that do NOT start with the "description" followed by a colon but still need to be aligned I came up with a way to format those lines using the same method. I concatenate that data using the carriage return and tab characters "\r\t" and then replace the tab character "\t" with my method. Note that I include the two blank spaces that follow the colon in this example in order to give the formatting method something to prepend to and that I am trimming the trailing "\r\t" before formatting the string.
The complete code section is shown below followed by a link to the example MessageBox output created by that code.
string results = "";
StringBuilder sb = new StringBuilder();
string longest = "Department: ";
foreach (EncounterInfo enc in lei)
{
results += enc.Description + " " + enc.ResultValue + " " + enc.ResultUnits + "\r\t";
}
results = results.TrimEnd(new char[] { '\r', '\t' });
results = results.Replace("\t", StringLengthFormat(" ", longest));
sb.AppendLine(StringLengthFormat("Result(s): ", longest) + results);
sb.AppendLine(StringLengthFormat("Patient: ", longest) + ei.PatientName);
sb.AppendLine(StringLengthFormat("Accession: ", longest) + ei.AccessionNumber);
sb.AppendLine(longest + ei.CollectionClassDept);
sb.AppendLine();
sb.AppendLine("Continue?");
dr = MessageBox.Show(sb.ToString(), "Add to Encounters", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
Example MessageBox with string length formatting
Based on the approach specified by Terrence Meehan, I rewrote the StringLengthFormat method as follow:
using System.Drawing;
using System.Windows.Forms;
enum Alignment { Left = 0, Right = 1};
static string StringLengthFormat(string inputString, string longestString,
Alignment alignment=Alignment.Left, string margin="")
{
Size textSizeMax = TextRenderer.MeasureText(longestString + margin, SystemFonts.MessageBoxFont);
Size textSizeCurrent = TextRenderer.MeasureText(inputString, SystemFonts.MessageBoxFont);
do
{
if (alignment == Alignment.Left)
{
inputString += " ";
}
else
{
inputString = " " + inputString;
}
textSizeCurrent = TextRenderer.MeasureText(inputString, SystemFonts.MessageBoxFont);
} while (textSizeCurrent.Width < textSizeMax.Width);
return inputString;
}
The differences are as follows:
Instead of System.Drawing.SystemFonts.DefaultFont, I use System.Drawing.SystemFonts.MessageBoxFont;
The parameter margin sets the distance between the columns (by transferring the required number of spaces);
The parameter alignment sets the alignment in the columns (left or right). If desired, the code can be supplemented so that the center alignment option also appears.
tring strMsg = "Machine :" + "TestMahine\t\nUser :" + "UserName";
MessageBox.Show(strMsg);

Categories

Resources