I have the following scenario.I am using App.config in Winforms and I have a value that is set to int (In settings). I want to use this value as a label text.
Am I correct that labels can only display string values?
This is what I have done here but not getting expected result (value to the label):
int ExclRate = Properties.Settings.Default.PriorExclTimer;
string ExclTime = ExclRate.ToString();
ExclTime = label60.Text;
PriorExclTimer is the type of the value in app.config.
I can make this work if I set the value in app.config to string, but that means I would have to convert from string to int in a much more sensitive part of the program, and I would rather not have to do that if possible. This is that line that works:
label60.Text = Properties.Settings.Default.PriorExclTimer;
I'm very new to C#, so I am really feeling my way around. Thanks...
In C# you cannot directly assign int to string. It has to always undergo conversion (either parse string to integer, or get a string out of integer).
As you say it's better to convert integer to a string for display purposes. Labels cannot directly show integer, so you will always need to convert it, or write some wrapper class if it's not enough.
Be aware that ToString() is culture specific, i.e. it will use the culture from the current thread. It might or might not be what you want. If you want InvariantCulture you can use ToString(CultureInfo.InvariantCulture).
P.S. As mentioned in the comments you can do various tricks like ExclRate + "", or in C#6 ${ExclRate}, but they are all basically converting an integer to string. I guess they all call ToString() inside.
int ExclRate = Properties.Settings.Default.PriorExclTimer;
label60.Text = ExclRate.ToString();
Code above will give you exception if PriorExclTimer is null or empty. So better you use int.TryParse to assign it to int. Not in this case, but ToString does not handle the null case, it gives exception. So you should try Convert.ToString instead.
While doing string manipulations you have to take care of culture and case (string case sensitive or insensitive)
This works for me:
int ExclRate = Properties.Settings.Default.PriorExclTimer;
label60.Text = ExclRate.ToString();
Many thanks for the insights on this topic. I will be manipulating data to and from a string a good bit for the project I am working on...
Related
Numerical formatting of int, double, decimal can be simply achieved via using Standard Numerical Formatter for example assuming Culture is "en-GB":
int value = 1000;
Console.WriteLine(value.ToString("C0")); // Would output £1,000
However I am wondering if there is a simple way to format a string to something of the same effect as above. For example:
string amount = "£2000"; // Would want to format to "£2,000"
Is there a way to format this string so that the thousands separator is added in the correct position?
Given it's a string I don't think numerical formatting would work without converting the string to a numerical data type beforehand:
var result = Int32.Parse("£2000", NumberStyles.AllowCurrencySymbol, new CultureInfo("en-GB"));
Console.WriteLine(result.ToString("C0", new CultureInfo("en-GB"))); // Outputs £2,000
However its a bit verbose to convert string to int then back to string. Is there is a simpler way to do this given that the starting string has the currency symbol?
Given it's a string I don't think numerical formatting would work without converting the string to a numerical data type beforehand
Indeed.
Is there is a simpler way to do this given that the starting string has the currency symbol?
No. And I seriously doubt that such a feature would ever be added and/or welcomed by the developer community. A formal specification for such a feature would be a complexity nightmare.
Of course, in your particular case, if you are sure that your string always consists of "currency symbol + sequence of digits without comma or period", you could develop a string-based solution optimized for your use case (for example, a fancy regular expression). However, I think that your current solution is both readable and maintainable and you would do your future self a favor by keeping it that way. If you need it multiple times, extract it into a method.
Struggling with the basics - I'm trying to code a simple currency converter. The XML provided by external source uses comma as a decimal separator for exchange rate (kurs_sredni):
<pozycja>
<nazwa_waluty>bat (Tajlandia)</nazwa_waluty>
<przelicznik>1</przelicznik>
<kod_waluty>THB</kod_waluty>
<kurs_sredni>0,1099</kurs_sredni>
</pozycja>
I already managed to load the data from XML into a nifty list of objects (kursyAktualne), and now i'm trying to do the math. I'm stuck with conversion.
First of all i'm assigning "kurs_sredni" to a string, trying to replace "," with "." and converting the hell out of it:
string kursS = kursyAktualne[iNa].kurs_sredni;
kursS.Replace(",",".");
kurs = Convert.ToDouble(kursS);
MessageBox.Show(kurs.ToString());
The messagebox show 1099 instead of expected 0.1099 and kursS still has comma, not dot.
Tried toying with some cultureInfo stuff i googled, but that was too random. I need to understand how to control this.
Just use decimal.Parse but specify a CultureInfo. There's nothing "random" about it - pick an appropriate CultureInfo, and then use that. For example:
using System;
using System.Globalization;
class Test
{
static void Main()
{
var french = CultureInfo.GetCultureInfo("fr-FR");
decimal value = decimal.Parse("0,1099", french);
Console.WriteLine(value.ToString(CultureInfo.InvariantCulture)); // 0.1099
}
}
This is just using French as one example of a culture which uses , as a decimal separator. It would probably make sense to use the culture of the origin of the data.
Note that decimal is a better pick for currency values than double - you're trying to represent an "artificial" construct which is naturally specified in base10, rather than a "natural" continuous value such as a weight.
(I would also be wary of a data provider who provides data in a non-standard format. If they're getting that wrong, who knows what else they'll get wrong. It's not like XML doesn't have a well-specified format for numbers...)
It is because Replace method returns new string with replaced characters. It does not modify your original string.
So you need to reassign it:
kursS = kursS.Replace(",",".");
Replace returns a string. So you need an assignment.
kursS = kursS.Replace(",", ".");
There is "neater" way of doing this by using CulturInfo. Look this up on the MSDN website.
You replace result isn't used, but the original value that doesn't contain the replace.
You should do:
kursS = kursS.Replace(",", ".")
In addition this method isn't really safe if there are thousands-separators.
So if you are not using culture settings you should do:
kursS = kursS.Replace(".", "").Replace(",", ".")
I have a text box named textBox1, and In a certain case, I want to convert the string in the textbox to an integer for later use as an integer.
It's throwing an error that I can't even understand. Here is a screenshot:
(Per Request) The code is:
this.textBox1.Text = string.Concat(Int.Where(c => Char.IsNumber(c)));
this.textBox1.Text = Convert.ToInt32(this.textBox1.Text);
I would really appreciate it if you could give me an answer or fix to my code, and explain why it doesn't/does work.
Convert.ToInt32 will, by design, return an integer, not a string.
If you're just storing the result back into the text box, there's no reason at all to convert it to a number only to convert it back to a string.
This would really only be useful if you wanted to do:
int value = Convert.ToInt32(this.textBox1.Text);
That being said, you might want to use Int32.TryParse instead. This allows you to check for formatting errors instead of having exceptions raised if the user types inappropriate values.
We have a requirement to display bank routing/account data that is masked with asterisks, except for the last 4 numbers. It seemed simple enough until I found this in unit testing:
string.Format("{0:****1234}",61101234)
is properly displayed as: "****1234"
but
string.Format("{0:****0052}",16000052)
is incorrectly displayed (due to the zeros??): "****1600005252""
If you use the following in C# it works correctly, but I am unable to use this because DevExpress automatically wraps it with "{0: ... }" when you set the displayformat without the curly brackets:
string.Format("****0052",16000052)
Can anyone think of a way to get this format to work properly inside curly brackets (with the full 8 digit number passed in)?
UPDATE: The string.format above is only a way of testing the problem I am trying to solve. It is not the finished code. I have to pass to DevExpress a string format inside braces in order for the routing number to be formatted correctly.
It's a shame that you haven't included the code which is building the format string. It's very odd to have the format string depend on the data in the way that it looks like you have.
I would not try to do this in a format string; instead, I'd write a method to convert the credit card number into an "obscured" string form, quite possibly just using Substring and string concatenation. For example:
public static string ObscureFirstFourCharacters(string input)
{
// TODO: Argument validation
return "****" + input.Substring(4);
}
(It's not clear what the data type of your credit card number is. If it's a numeric type and you need to convert it to a string first, you need to be careful to end up with a fixed-size string, left-padded with zeroes.)
I think you are looking for something like this:
string.Format("{0:****0000}", 16000052);
But I have not seen that with the * inline like that. Without knowing better I probably would have done:
string.Format("{0}{1}", "****", str.Substring(str.Length-4, 4);
Or even dropping the format call if I knew the length.
These approaches are worthwhile to look through: Mask out part first 12 characters of string with *?
As you are alluding to in the comments, this should also work:
string.Format("{0:****####}", 16000052);
The difference is using the 0's will display a zero if no digit is present, # will not. Should be moot in your situation.
If for some reason you want to print the literal zeros, use this:
string.Format("{0:****\0\052}", 16000052);
But note that this is not doing anything with your input at all.
I need a way to Parse an string into an integer value in c#. The problem is the user chosses a string from a combo box which contains strings such as "AAAAA" or "5". That means only at run time it is known if the parameter is a real string or an string which can be parsed to an integer. I tried around with reflection and have the fitting Parameter object.
ParameterInfo p = ps[i];
Type t = p.ParameterType;
I don't know how to go on from there or if it even is possible. I can't use if else statments because the program is supposed to load other interfaces with new parameters as well. So I could handle the default ones with if else statmentes but when a new interface with new Methodinfos is loaded that dos not work anymore.
I'm not usre that understood all your constraints. However you can parse string by using Int32.TryParse in case target string is not necessarily valid.
Int32.TryParse whould help you with that
To parse a string into an integer, you can use Convert.ToInt32(string_var), or any of the other conversion methods. See here for more.