Search code examples
c#.netdatagridviewint32

Problems When Converting String that Contains a Period (.) to Int32 in C#


I'm creating a POS (Point Of Sale) and I've come across a problem when trying to convert the price "0.60" to an integer.

Data Background: All the Data for the Data Source is from a MySQL database that I have setup and connected with no problems.

The Price is Stored in a TextBox and is formatted as such "0.60", I believe that this is the reason why it isn't being converted. I keep getting the message below.

Additional information: Input string was not in a correct format.

        //Puts the Price Into a String.
        string NewPrice = txtPrice.Text;

        //Converts The Quantity In the TextBox field to a numbers.
        Quantity = Convert.ToInt32(txtQuant.Text);

        //Incorrect Format & Attempt One.
        //Price = Convert.ToInt32(NewPrice); <--- Problem.
        //Price = int.Parse(NewPrice);

        // I've also tried this method below with two '0' inside the { } brackets.
        // But Still No Luck.
        Price = Convert.ToInt32(string.Format("{0.00}",txtPrice.Text)); // <--- Problem.

        // Times Price & Quantity to get Total Price (0.60 * 2 = 1.20)
        TotalSingleItemPrice = Price * Quantity;

        // The Single Item Price is added into the overall total.
        TotalPrice += TotalSingleItemPrice;

        // Converts Total Item Price to String from Int.
        string TotalPriceStr = Convert.ToString(TotalSingleItemPrice);           

        // Puts TextBoxes / Strings Into One String array (I think).
        string[] InizialItemList = new string[] { cmboInitItem.Text, Convert.ToString(Price), Convert.ToString(Quantity), TotalPriceStr};

        // Adds The String Array Into the Data Grid View.
        DGVIIL.Rows.Add(InizialItemList);

I've tried to use the string.Format("{0.00}",txtPrice.Text) setup to combat this problem, I just can't see what I have over looked. I would like the Price to appear in my DataGridView - DGVIIL, as 0.60 if possible.


Solution

  • 0.60 is not an integer, the error is right on

    Alternatives:

    Decimal d = Decimal.Parse(txtPrice.Text);
    

    Or even better:

    Decimal d;
    if ( decimal.TryParse(txtPrice.Text, out d) == false ){
      //handle bad number...
    }