Convert.ToInt32(String) in C# not working? - c#

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.

Related

C# Convert int to string and use in a Label

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...

C# format to thousand seperator

I am trying to format user input to a thousand seperator format. I tried the code here, but it keeps breaking the application:
Amt.Text = String.Format("{0:0,0.00}", Convert.ToDouble(Amt));
So when the user inputs 3566412, then it needs to convert automatically to 3,566,412
You are trying to convert the control (named Amt) to a double, which is a bad idea since you want to convert the text of the control (Amt.Text). I would suggest to use a decimal since that is more precise and will not cause floating point issues:
Amt.Text = String.Format("{0:0,0.00}", Convert.ToDecimal(Amt.Text));
Another thing to consider is to use a control that can mask itself, so you don't need to replace the text yourself every time.
You might want to check out Standard Numeric Format Strings at MSDN
Then you could do something like
Amt.Text = inputnumber.ToString("N");
Which will format 3566412 to 3,566,412.0
If you want to take it directly from the textbox, you could do something like this, which checks if the text can be parsed before setting the text
double result = 0;
if (double.TryParse(Amt.Text, out result)
{
Amt.Text = result.ToString("N");
}

Input String is not correct format when trying to type in a hyphen first

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.

Formatting textbox c# and using it unformatted value

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.

state at compile time not known

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.

Categories