Click here to Skip to main content
15,881,856 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Im having a bit of trouble with a formatting moment.
I followed the example I was given exactly, but am still not finding what makes the specific line come up as an error. The line with the stars is the one I'm having trouble with. It's just coming up with a System.FormatException. Thanks yall!

Here are two lines from the document I'm trying to read when that float.Parse statement isn't running correctly
****QUICK-Stop|Ikura|31|24|
QUICK-Stop|Gorgonzola Telino|12.5|15|****




private void cmboboxlist_SelectedIndexChanged(object sender, EventArgs e)
{
    string [] names = new string[10];
    float[] subtotals = new float[10];
    string [] fields;
    int index = 0;
    float subtotal;
    string frmStr, currentLine;
    StreamReader ReportReader = new StreamReader("PurchaseReport.txt");
    lstboxdisplay.Items.Clear();
    frmStr = "{0,-20}{1,10}{2,10}{3,20:N1}";

    while (ReportReader.EndOfStream == false)
    {

        currentLine = ReportReader.ReadLine();
        fields = currentLine.Split('|');

     ****   subtotal = float.Parse(fields[2]) + float.Parse(fields[3]);
        names[index] = fields[0];
        subtotals[index] = subtotal;
        index = index + 1;

        lstboxdisplay.Items.Add(String.Format(frmStr, fields[0], fields[1], fields[2], fields[3], subtotal));
    }


What I have tried:

I've tried changing the formats of the outputs, but it just keeps saying they're formatted incorrectly, though, on another document I have as an example, this format works fine.
Posted
Updated 14-Dec-22 0:01am
v3
Comments
PIEBALDconsult 13-Dec-22 20:59pm    
Check the values you are trying to parse.
BillWoodruff 13-Dec-22 22:14pm    
show an example of a line of the data file, and show the output that is not formatted as you expect it to.

fields[2] and/or fields[3] is not what you think it is. Set a breakpoint on that line and run the code. When the debugger stops on that line, hover the mouse over each of the variables you're trying to parse the content of and see what they contain.
 
Share this answer
 
C#
****   subtotal = float.Parse(fields[2]) + float.Parse(fields[3]);

Don't use Parse, as it just crashes the application if the data is incorrect. Change it to TryParse:
C#
float temp = 0;
if (!float.TryParse(fields[2], out temp)
{
    // display a message showing the invalid data, and return from the method
}
subtotal = temp;
if (!float.TryParse(fields[3], out temp)
{
    // display a message showing the invalid data, and return from the method
}
subtotal += temp;

See Single.TryParse Method (System) | Microsoft Learn[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900