I'm trying to make a hex to decimal converter for large amounts of hex numbers.
{
textBox1.Text = textBox1.Text.Replace("-", "");
textBox1.Text = textBox1.Text.Replace(" ", "");
if (textBox1.TextLength > 0)
{
textBox2.Text = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.HexNumber).ToString();
}
textBox3.Text = textBox2.Text.ToString().Replace(Environment.NewLine, ", ");
}
works fine on single line.
Error when trying to convert multiple lines
System.FormatException: Input string was not in a correct format.
If you're using a multiline textbox, try replacing the newline characters of its' value as well, like this:
textBox1.Text = textBox1.Text.Replace("\r\n", ""); // For Windows
textBox1.Text = textBox1.Text.Replace("\n", ""); // For Unix/Linux
Related
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
I have values from a textbox :
"r, 00.00m,0000521135Hz,0000000000c,0000000.000s, 025.1C"
and I want to make each value show in another textboxes like this:
textbox 1:
a: "00.00"
textbox 2:
b: "0000521135"
textbox 3:
c: "0000000.000"
textbox 4:
d: "025.1"
I can do this in arduino using parseInt(),
I wonder how to do this in c#, any help?
you can use a string.split() function to extract value from first textbox.
string baseStr = "r, 00.00m,0000521135Hz,0000000000c,0000000.000s, 025.1C";
List<string> colStr= test.Split(new char[','], StringSplitOptions.RemoveEmptyEntries);
and then remove alphabet using regular expression
using System.Text.RegularExpressions;
...
Textbox1.Text = Regex.Replace(colStr[1], "[A-Za-z]", "");
Textbox2.Text = Regex.Replace(colStr[2], "[A-Za-z]", ""));
...
This will give you the idea how to put the data in the textboxes. I have done it for a string variable.
string s1 = "r, 00.00m,0000521135Hz,0000000000c,0000000.000s, 025.1C";
string[] spliteds1 = s1.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string txt1 = "";
foreach(string elem in spliteds1)
{
if(Regex.Replace(elem, "[^0-9.]", "") != "")
{
txt1 = txt1 + Regex.Replace(elem, "[^0-9.]", "") + ",";
}
}
This code will put the in txt1 with comma seperator. You can run your loop for textboxes.
Hope this helps
I have the value 4,59,999/-. My code is
if (Regex.IsMatch(s,#"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
string value = Regex.Replace(s, #"[^\d]", " ");
textBox2.Text= value;
}
Output is: 4 59 999, I need it to be 459999 (without "," , "/" , "-" and " ").
How about without regex?
var s = "4,59,999/-";
var array = s.Where(c => char.IsDigit(c)).ToArray();
or shorter
var array = s.Where(char.IsDigit).ToArray();
And you can use this array in a string(Char[]) constructor.
var result = new string(array); // 459999
You don't need regex, you could use:
textBox2.Text = String.Concat(s.Where(Char.IsDigit));
Much better is to use decimal.Parse/TryParse:
string s = "4,59,999/-.";
decimal price;
if (decimal.TryParse(s.Split('/')[0], NumberStyles.Currency, NumberFormatInfo.InvariantInfo, out price))
textBox2.Text = price.ToString("G");
Just replace with empty string.
string value = Regex.Replace(s, #"[^\d]", ""); // See the change in the replace string.
textBox2.Text= value;
Note You don't require the if as the regex replace will work only if there is a match for non digits ([^\d])
Should just be a case of replacing it with an empty string instead of a space?
Regex.Replace(s, #"[^\d]", String.Empty);
Currently you're replacing these characters with a space. Use an empty set of quotes instead.
if (Regex.IsMatch(s,#"\b[1-9]\d*(?:,[0-9]+)*/?-?"))
{
string value = Regex.Replace(s, #"[^\d]", "");
textBox2.Text= value;
}
You are replacing the ",", "/", "-" and " " with a white space. Try this instead:
string value = Regex.Replace(s, #"[^\d]", "");
Hope this helps.
Linq is a possible solution:
String s = "4,59,999/-";
...
textBox2.Text = new String(s.Where(item => item >= '0' && item <= '9').ToArray());
Try something like this it will work 100% in php so just change some syntax for C#
<?php
$str = "4,59,999/-.";
echo $str = preg_replace('/[^a-z0-9]/', '', $str);
?>
I have li inside it i contain td.
var values = '';
$("#list4 li.add table .mytd").each(function () {
values = $(this).html() + '|' + values;
});
document.getElementById("MainContent_uscRetailParameters_hdRetailCustomerGroup").value = values;
__doPostBack('<%=txtRCCode.ClientID%>', '');
when I capture in hidden field it come like this
[alot of spaces]CHARMINSENSITIVE-1
with lot of spaces how can i retrieve the exact value in all browser. this space not found in Internet explorer. but in firefox it comes with spaces how could i capture the exact td value.
string lvValues = hdProductGroup.Value;
//string trim = lvValues.Replace(" ", "");
string trim = lvValues.Replace("\r", "");
trim = trim.Replace("\r", "");
trim = trim.Replace("\n", "");
trim = trim.Replace("\t", "");
string str = trim;
string[] list = str.Split('|');
You could trim it in Jquery? Try something like the following:
values = $.trim($(this).html() + '|' + values);
Or at the server using something like:
value = value.Trim();
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);