Input String was not in a correct form - c#

There are two text boxes called unitprice.txt and quantity.txt. there is another textbox called total.txt which keeps on getting updated as the when ever the user input unit price and quantity.
Oonce the user input these two those two textboxes are getting empty and total.txt getting updated by the total. it needs to be done continuously but in my code it is not and saying
INPUT STRING WASN'T IN A CORRECT FORM.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text) * int.Parse(quantitytxt.Text);
sum = int.Parse(total.Text) + tot;
total.Text = sum.ToString();
once the user enters the unit price and quantity total text boxe is updated by the toal. and again user enters the second item's unit price and quantity then previous value in total text box needs to be updated which means that new total generated from the second item needs to be added to previous total.(2500+3000=5500)
Hey it was solved but in this way.
int sum = 0;
private void button2_Click(object sender, EventArgs e)
{
try
{
sum += int.Parse(qtytxt.Text) * int.Parse(unitprice.Text);
total.Text = sum.ToString();
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}

First of all check if text box value is not coming empty or not,If it is coming empty then set 0 as default while converting to parse Int otherwise it will show exception. see below code it will help you.
int tot = 0;
int sum = 0;
tot = int.Parse(string.IsNullOrEmpty(unitprice.Text.Trim()) ? "0" : unitprice.Text.Trim()) * int.Parse(string.IsNullOrEmpty(quantitytxt.Text.Trim()) ? "0" : quantitytxt.Text.Trim());
sum = int.Parse(string.IsNullOrEmpty(total.Text.Trim()) ? "0" : total.Text.Trim()) + tot;
total.Text = sum.ToString();

You are trying to parse a string value that is textbox value to integer, so you shouldn't do like the above, because may be it contains empty string or null value too. So, follow the below method of conversion, so that errors may not occur.
tot = Convert.ToInt32(Convert.ToString(unitprice.Text)) * Convert.ToInt32(Convert.ToString(quantitytxt.Text));
Why you should follow the above method is, the Convert.ToString() will handle the null values and convert the null values to an Empty string and the Convert.ToInt32() will convert an empty string to 0 value.

If you want another option, you can try Int32.TryParse(a_string_here, an_out_int_here);
For more, look at the documentation here:MSDN TryParse
It'll take a string and try to parse it to a valid int... if it fails, it returns 0.
int a ;
Int32.TryParse("5",out a);
System.Out.WriteLine("a="+a); // Will be: a=5
Int32.TryParse("e",out a);
System.Out.WriteLine("a="+a); // Will be: a=0

First of all check if text box value is not coming empty, as if you will parse it into Int and when its empty, there will be this or similar exception.
int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text!=String.Empty?unitprice.Text:"0") * int.Parse(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = int.Parse(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();
You can also try:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text!=String.Empty?unitprice.Text:"0") * Convert.ToInt32(quantitytxt.Text!=String.Empty?quantitytxt.Text:"0");
sum = Convert.ToInt32(total.Text!=String.Empty?total.Text:"0") + tot;
total.Text = sum.ToString();

Try this:
int tot = 0;
int sum = 0;
tot = Convert.ToInt32(unitprice.Text.Replace(" ", "")) * Convert.ToInt32(quantitytxt.Text.Replace(" ", ""));
sum = Convert.ToInt32(total.Text.Replace(" ", "")) + tot;
total.Text = sum.ToString();
If this throws an exception your textboxes probably has unwanted characters (i.e. commas: "1,000.00" or letters) or empty that makes the convertion throw an exception.

the problem is...if the string is other than numbers ............
Any string value other than numbers will show an error saying INPUT STRING WASN'T IN A CORRECT FORM!!!.
there is a solution for this.....insert your code inside try catch block
try{ your code here}catch(FormatException){}
or find another mechanism to avoid strings other than numbers....

Int32.Parse() will throw an exception if the input value is not an integer. Use Int32.TryParse() to convert a value without throwing an exception. If the conversion fails, TryParse() will return false and zero will be returned:
int intValue = -1;
bool result;
result = Int32.TryParse("23", out intValue); // result = true, intValue = 23
result = Int32.TryParse("AB", out intValue); // result = false, intValue = 0
EDIT: For your specific case, try this:
int tot = 0;
int sum = 0;
int price = 0; // output parameter to receive value
int quantity = 0; // output parameter to receive value
int total = 0; // output parameter to receive value
TryParse(unitprice.Text, out price); // price contains the unit price value
TryParse(quantitytxt.Text out quantity); // quantity contains the quantity value
TryParse(total.Text, out total); // total contains the total value
tot = price * quantity;
sum = total + tot;
total.Text = sum.ToString();

int tot = 0;
int sum = 0;
tot = int.Parse(unitprice.Text+"0") * int.Parse(quantitytxt.Text+"0");
sum = int.Parse(total.Text+"0") + tot;
total.Text = sum.ToString();
Try this code.

Related

How do I divide integers and not get a 1

Just a simple console program in c#. The answer is always 1, but I want to get the right answer and the answer to always be an integer, nothing but whole numbers here.
Console.Write("Ange dagskassa (kr): ");
string inlasning = Console.ReadLine();
int dagskassa = int.Parse(inlasning);
Console.Write("Ange nuvarande lunchpris (kr): ");
string inlasning2 = Console.ReadLine();
int lunchpris = int.Parse(inlasning);
double antalGaster = dagskassa / lunchpris;
Console.WriteLine("Antal gäster: " + antalGaster + "st.");
The problem here is that you're converting the same number twice, to two different variables, and then dividing them, so the answer will always be 1:
int dagskassa = int.Parse(inlasning);
int lunchpris = int.Parse(inlasning); // You're parsing the same input as before
To resolve this, convert the second input for the lunch price:
int dagskassa = int.Parse(inlasning2); // Parse the *new* input instead
You'll need to cast your ints to double in order for the above to work. For example,
int i = 1;
int j = 2;
double _int = i / j; // without casting, your result will be of type (int) and is rounded
double _double = (double) i / j; // with casting, you'll get the expected result
In the case of your code, this would be
double antalGaster = (double) dagskassa / lunchpris;
To round to the lowest whole number for a head count, use Math.Floor()
double antalGaster = Math.Floor((double) dagskassa / lunchpris);

Get a single string out of a ListBox Item

I have a ListBox with X Items in it. An Item is build up like String, double, double. I want that the item with the smalles value of the second double gets shown together with its string in a Label.
An example Item: Name Value1 Value2
So every part is devided by spaces. The code works only for getting the smallest value of the second double yet, but doesnt take the string of that item.
The function of vName doesn't work.
private void bVergleich_Click(object sender, RoutedEventArgs e)
{
if (listBox.Items.Count <= 0)
{
MessageBox.Show("Bitte erst Einträge hinzufügen.");
}
else
{
int anzahl = listBox.Items.Count;
string str = listBox.Items[anzahl].ToString();
string vName = str.Substring(0, str.IndexOf(" ") + 1);
var numbers = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').First(), NumberStyles.Currency, CultureInfo.CurrentCulture));
decimal minValue = listBox.Items.Cast<string>().Select(obj => decimal.Parse(obj.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture)).Min();
lVergleich.Content = vName + " " + minValue + "€";
}
}
Any ideas how I can get the string too?
I will try using your code example. You could use the old school approach and run with a for-loop through all entries.
private void bVergleich_Click(object sender, RoutedEventArgs e)
{
if (listBox.Items.Count <= 0)
{
MessageBox.Show("Bitte erst Einträge hinzufügen.");
}
else
{
List<decimal> tmpListe = new List<decimal>();
int anzahl = listBox.Items.Count;
for (int i = 0; i < anzahl; i++)
{
string str = listBox.Items[i].ToString();
// collect all the second double values
tmpListe.Add(decimal.Parse(str.Split(' ').Last(), NumberStyles.Currency, CultureInfo.CurrentCulture));
}
// get the minimal value and its index
decimal minValue = tmpListe.Min();
int index = tmpListe.IndexOf(tmpListe.Min());
// use the index to get the name
string str2 = listBox.Items[index].ToString();
string vName = str2.Substring(0, str2.IndexOf(" ") + 1);
// write down your comparison
lVergleich.Content = vName + " " + minValue + "€";
}
}
This should display you the first lowest value in your List.
personally I would also suggest to use a custom class with 3 properties and an overridden ToString method for display. Then collect all the items in a generic List and bind this List to the ListBox.
You can sort your collection by the desired value and take the first element in sequence
List<string> list = listBox.Items.ToList();
list.Sort((x1, x2) => decimal.Compare(decimal.Parse(x1.Split(' ')[1]), decimal.Parse(x2.Split(' ')[1])));
string x = list.First();
Or just
string result = listBox.Items.OrderBy(y => decimal.Parse(y.Split(' ')[1])).First();

How can I display decimal position based on my decimal position value?

decimal value = 10;
int decimalPosition= 3; //this decimalPosition will be dynamically change.
decimal formatted = Math.Round(value, decimalPosition);
if decimalPosition =3;
I need to display formatted value like : 10.000.
if decimalPosition =5;
I need to display formatted value like : 10.00000.
Note: I must use Round function.
decimal value has no format assigned - it is just a numeric value. You can specify the format it's being printed out with, but you have to do it while printing or when the string is being created:
decimal value = 10;
int decimalPosition = 3; //this decimalPosition will be dynamically change.
decimal formatted = Math.Round(value, decimalPosition);
string format = string.Format("{{0:0.{0}}}", string.Concat(Enumerable.Repeat("0", decimalPosition).ToArray()));
string formattedString = string.Format(format, formatted);
Console.WriteLine(formattedString);
Prints 10.000 into console.
Another way of specifying format like that:
var format = string.Format("{{0:f{0}}}", decimalPosition);
You can try something like this:-
decimal.Round(yourValue, decimalPosition, MidpointRounding.AwayFromZero);
u can try it:--
decimal value = 10;
int decimalPosition = 3; //this decimalPosition will be dynamically change.
string position = "";
for (int i = 0; i < decimalPosition; i++)
{
position += "0";
}
string newValue = value.ToString() + "." + position;
decimal formatted = Convert.ToDecimal(newValue);
Use FORMATASNUMBER(Value, decimalPosition) instead of math.round
Sorry, I forgot it was c# not VB
But you can read about it here on MSDN
http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.formatnumber(v=VS.80).aspx
The command is String.FormatNumber(blah blah blah)
and the ACTUAL declaration is...
public static string FormatNumber (
Object Expression,
[OptionalAttribute] int NumDigitsAfterDecimal,
[OptionalAttribute] TriState IncludeLeadingDigit,
[OptionalAttribute] TriState UseParensForNegativeNumbers,
[OptionalAttribute] TriState GroupDigits
)

Error message during calculation

Anyone, please take a look at my line of code.
int totalValue = 0;
totalValue = int.Parse(Label9.Text) * int.Parse(Label6.Text);
Label8.Text = **totalValue**;
Why I get error message?
cannot implicitly convert type int to string.
Thanks for ya help.
You should convert int to string. Something like this:
Label8.Text = totalValue.ToString();
Or this:
Label8.Text = totalValue + "";
try this:
int totalValue = 0;
totalValue = int.Parse(Label9.Text) * int.Parse(Label6.Text);
Label8.Text = totalValue.ToString();
Using the text directly is not a good way, what if parsing fails?
Use
int? val1=GetInt32(Label9.Text);
int? val2=GetInt32(Label6.Text);
if(val1!=null&&val2!=null)
{
int totalValue = 0;
totalValue = val1+val2;
Label8.Text = totalValue.ToString();
}
//You can also write your own logic on the TextBoxs if they did not contain a valid value by checking if val1 or val2 are null or not
Using the function to return int value if the input can be converted.
public int? GetInt32(string s)
{
int i;
if (Int32.TryParse(s, out i)) return i;
return null;
}
That's because totalValue is an int.
Try this:
Label8.Text = totalValue.ToString();

Add numbers in c#

i have a numerical textbox which I need to add it's value to another number
I have tried this code
String add = (mytextbox.Text + 2)
but it add the number two as another character like if the value of my text box is 13 the result will become 132
The type of mytextbox.Text is string. You need to parse it as a number in order to perform integer arithmetic, e.g.
int parsed = int.Parse(mytextbox.Text);
int result = parsed + 2;
string add = result.ToString(); // If you really need to...
Note that you may wish to use int.TryParse in order to handle the situation where the contents of the text box is not an integer, without having to catch an exception. For example:
int parsed;
if (int.TryParse(mytextbox.Text, out parsed))
{
int result = parsed + 2;
string add = result.ToString();
// Use add here
}
else
{
// Indicate failure to the user; prompt them to enter an integer.
}
String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();
You need to convert the text to an integer to do the calculation.
const int addend = 2;
string myTextBoxText = mytextbox.Text;
var doubleArray = new double[myTextBoxText.ToCharArray().Length];
for (int index = 0; index < myTextBoxText.ToCharArray().Length; index++)
{
doubleArray[index] =
Char.GetNumericValue(myTextBoxText.ToCharArray()[index])
* (Math.Pow(10, (myTextBoxText.ToCharArray().Length - 1) - index));
}
string add =
(doubleArray.Aggregate((term1, term2) => term1 + term2) + addend).ToString();
string add=(int.Parse(mytextbox.Text) + 2).ToString()
if you want to make sure the conversion doesn't throw any exception
int textValue = 0;
int.TryParse(TextBox.text, out textValue);
String add = (textValue + 2).ToString();
int intValue = 0;
if(int.TryParse(mytextbox.Text, out intValue))
{
String add = (intValue + 2).ToString();
}
I prefer TryPase, then you know the fallback is going to be zero (or whatever you have defined as the default for intValue)
You can use the int.Parse method to parse the text content into an integer:
String add = (int.Parse(mytextbox.Text) + 2).ToString();
Others have posted the most common answers, but just to give you an alternative, you could use a property to retrieve the integer value of the TextBox.
This might be a good approach if you need to reuse the integer several times:
private int MyTextBoxInt
{
get
{
return Int32.Parse(mytextbox.Text);
}
}
And then you can use the property like this:
int result = this.MyTextBoxInt + 2;

Categories

Resources