I am trying to align values.
I wonder why this happen :
string value = "";
value += string.Format("{0,-10}", "value");
value += string.Format("{0,5}", "value");
value += Environment.NewLine;
value += string.Format("{0,-8}", "val");
value += string.Format("{0,7}", "value");
MessageBox.Show(value);
If i check value before i do "MessageBox.Show() it is correct. The result is:
value value
val value
As they should be, but when i do MessageBox.show() then they get like this :
value value
val value
I really cant understand why it changes the string with show()? Same thing happens when i am trying to print "value", then it doesnt align correct.
Btw: this is just a test code so you could understand the problem that i am having with the real code.
This might be caused by the fact that the font used in the message box is not monospaced, meaning that each character takes an equal amount of horizontal space. The font you are using in the Visual Studio debugger probably is, which is why the padding looks entirely different.
You could try if using tabs instead of spaces for your formatting gives better results.
That's because the font used by MessageBox.Show doesn't have a fixed width...
According to this answer the way to go is using \t as a column seperator.
This definitely involves checking the length of all the words of each single column. This way you would know whether to use a single \t or double \t\t etc.
Related
The screenshot sums up the problem:
I have no control over the retrieved value. It comes in with some funky format that I can't figure out and the parsing fails even though it looks totally normal. Typing the value in manually works just fine.
How can I "normalize" the retrieved value so Decimal.Parse does not fail?
For reference, here is the string that fails (copied and pasted):
"10.00"
First I would check your regional settings to eliminate anything as simple as a difference in expected decimal separator.
If that draws a blank then if the string 10.00 parses successfully then a string that looks like 10.00 but which fails to parse cannot actually be 10.00.
Inspect and determine the character code of each character of the string and confirm that it really is 10.00 and not some exotic Unicode that has the same appearance but which is actually different (which may also include characters which are not even visible when displayed).
You might have some kind of special character hidden in the string you are retrieving.
Try this:
Double.Parse(Regex.Replace(decimalValue, #"[^0-9.,]+", ""))
You might need to add using statement for System.Text.RegularExpressions
I would replace only the one problematic character, that is the safest option:
s = s.Replace("\u200E", "");
As Jeroen Mostert mentioned in a comment, there is a non-printed character in your decimalValue.
This is a similar question which should help you deal with that.
https://stackoverflow.com/a/15259355/7636764
Edit:
Using the the string output = new string(input.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray()); part of the solution, but also include in || char.IsPunctuation(c) after IsDigit will get your desired result.
I got some problems with getting caret index of TextBox in Windows Store App(WP 8.1).
I need to insert specific symbols to the text when button is pressed.
I tried this:
text.Text = text.Text.Insert(text.SelectionStart, "~");
But this code inserts symbol to the beginning of text, not to the place where caret is.
UPDATE
I updated my code thanks to Ladi. But now I got another problem: I'm building HMTL editor app so my default TextBlock.Text is: <!DOCTYPE html>\r\n<html>\r\n<head>\r\n</head>\r\n<body>\r\n</body>\r\n</html>
So for example when user inserts symbol to line 3, symbol is inserted 2 symbols before caret; 3 syms before when caret is in line 4 and so on. Inserting works properly when symbol is inserted to the first line.
Here's my inserting code:
Index = HTMLBox.SelectionStart;
HTMLBox.Text = HTMLBox.Text.Insert(Index, (sender as AppBarButton).Label);
HTMLBox.Focus(Windows.UI.Xaml.FocusState.Keyboard);
HTMLBox.Select(Index+1,0);
So how to solve this? I guess new line chars making trouble.
For your first issue I assume you changed the TextBox.Text before accessing SelectionStart. When you set the text.Text, text.SelectionStart is reset to 0.
Regarding your second issue related to new lines.
You could say that what you observe is by design. SelectionStart will count one "\r\n" as one character for reasons explained here (see Remarks section). On the other hand, method string.Insert does not care about that aspect and counts "\r\n" as two characters.
You need to change slightly your code. You cannot use the value of SelectionStart as the insert position. You need to calculate the insert position accounting for this behavior of SelectionStart.
Here is a verbose code sample with a potential solution.
// normalizedText will allow you to separate the text before
// the caret even without knowing how many new line characters you have.
string normalizedText = text.Text.Replace("\r\n", "\n");
string textBeforeCaret = normalizedText.Substring(0, text.SelectionStart);
// Now that you have the text before the caret you can count the new lines.
// that need to be accounted for.
int newLineCount = textBeforeCaret.Count(c => c == '\n');
// Knowing the new lines you can calculate the insert position.
int insertPosition = text.SelectionStart + newLineCount;
text.Text = text.Text.Insert(insertPosition, "~");
Also you should make sure that SelectionStart does not exhibit similar behavior with other combinations beside "\r\n". If it does you will need to update the code above.
I am trying to put a negative number in a textbox, however whenever i click on the textbox and try to type for they hyphen it creates the error, also I don't want it to create this same error if i accidentally leave the textbox blank. as it has done before
TextBox tbox = this.Controls.Find("Team" + r.ToString() + "Q" + c.ToString(), true).FirstOrDefault() as TextBox;
int t1 = Convert.ToInt32(tbox.Text);
if (r == 1) team1score += t1;`
Yes, it's probably because when you type -, the CalculateTotals method is called and it tries to convert - to an integer, and fails. You don't show how you're doing the conversion, which is the most important part of your code. You probably should do something like this:
int myInt;
if (!int.TryParse(senderTB.Text, out myInt))
{
// The value in the textbox isn't an integer.
// Use 0 as the default.
myInt = 0;
}
That's not entirely correct, though, because the user might type something like 4000000000, which is larger than an int.
A quick fix would be to modify your regular expression so that it requires at least one number:
Regex reg = new Regex(#"^-?[0-9]+$");
Replacing the * with a + won't allow just a hyphen to match. This will fix your immediate problem, but it's not complete error checking. But it might be good enough for your purposes.
In general, you can easily use regular expressions to validate the form of a signed integer (i.e. an optional hyphen followed by one or more digits), but it's very difficult to use regular expressions to make sure the number is within the range of a signed integer. Making sure that the number is not less than -2147483648 or greater than 2147483647 is rather difficult to do with regular expressions.
You probably want a combination of the approaches: use the regular expression to prevent the user from typing illegal characters into the text box, and use int.TryParse to validate the number in your computeTotals method. And rather than defaulting to a value of 0, have the program display a message box informing the user of the error.
I´m using some textboxes to show totals, subtotals and discounts. I´m converting decimals to string to represent them in the textbox. Also, I would like to have the "$" at the beginning.
I have achieved this by using this:
tbx_total.Text = total.ToString("$ ##0.##");
Graphically, this is working great, but my big problem is that I need that textbox value to calculate other ones. Basically, I get a formatting error during runtime when I try to convert that textbox text to decimal. Obviously, this is due to the ToString("$ ##0.##") format. Is there any way to get the value without the format?
One simple solution will be:
tbx_total.Text = total.ToString("$ ##0.##");
tbx_total.Tag = total;
Then use tbx_total.Tag property for further usage.
When reading it back in you can parse with NumberStyles to get your desired effect. There is a number of bit-wise operations on NumberStyles so I suggest researching how to use them for more flexibility:
double.Parse(total, NumberStyles.Currency);
Also I tend to like this for formatting currency a bit more but purely stylistic.
String.Format("{0:C}", total);
Note: Parsing back and forth does incur some overhead so depending on the amount of data it may be more wise to offload the value to an object and reference that when you need the decimal value again.
As an alternative, you can do this, whenever you read the value:
double value = 0;
if (!double.TryParse(tbx_total.Text.TrimStart(new char[] { '$', ' ' }), out value))
{
//Ooops... not a valid number
}
So here you basically remove the added '$' and space before the number enabling you to parse it as a double. This way you can check if the number has been entered correctly (provided that the user can edit the textbox.
I think you should store your original values (decimal) in a DataTable or some other collection and use these values to calculate what you need.
So you can format decimal values in any format you like without warry about how to convert back from strings.
I am trying to align values. I wonder why this happen :
string value = "";
value += string.Format("{0,-10}", "value");
value += string.Format("{0,5}", "value");
value += Environment.NewLine;
value += string.Format("{0,-8}", "val");
value += string.Format("{0,7}", "value");
Print(value);
If i check value before i "Print" it is correct. The result is:
value value
val value
As they should be, but when i print "value" to my printer then they get like this :
value value
val value
I really cant understand why it changes the string when i print the text?
I have tried to use "\t" but my printer dont seem to understand "\t" because the tabs isnt printed out.
Btw: this is just a test code so you could understand the problem that i am having with the real code.
your console uses fixed width fonts where your printer does not (at least by default). So spaces take up less space on your printer and your letters take up more or less space based on their actual width.
This could be caused by a font that uses different character widths. In non-fixed-width fonts, spaces are often narrower than letters and numbers, so it might seem that spaces are missing. Consider using Lucida Console or another fixed-width font.