C#读取CSV计算薪资并显示到ListBox时抛出未处理异常求助
Hey there! Let's fix that exception and get your payroll calculator working properly. The immediate crash comes from a syntax error in your formatting code, but we’ll also clean up a few logic bugs that would cause weird results down the line.
1. Fix the Format String Syntax Error (Direct Exception Cause)
The line where you build DisplayPayroll has unclosed curly braces in the format string. This is why you’re seeing an unhandled exception. Here’s the broken line:
string DisplayPayroll = String.Format("{0,-18}{1,14:c}{2,11:C{3,13:c}", emp.FirstName + " " + emp.LastName, HoursWorked, PayRate, GrossPay);
Notice the {2,11:C part is missing a closing }. We’ll also fix the alignment of the format specifiers to match your header properly:
string DisplayPayroll = String.Format("{0,-18}{1,14:F2}{2,11:C}{3,13:C}", emp.FirstName + " " + emp.LastName, emp.HoursWorked, emp.PayRate, grossPay);
2. Fix Pay Calculation Logic (Variable Misassignment)
Your current logic mixes up what variables represent—you’re storing pay amounts in HoursWorked and PayRate, which will make your ListBox columns show incorrect data. Let’s rename variables for clarity and fix the overtime math:
foreach (Employee emp in EmployeeList) { double regularPay = 0.0; double overtimePay = 0.0; double grossPay = 0.0; // Check for Hourly or Salary pay type if (emp.PayType == "Hourly") { if (emp.HoursWorked > 40.0) { regularPay = emp.PayRate * 40.0; // Pay for first 40 hours overtimePay = emp.PayRate * 1.5 * (emp.HoursWorked - 40.0); // Overtime at 1.5x rate (adjust if needed) } else { regularPay = emp.PayRate * emp.HoursWorked; // No overtime overtimePay = 0.0; } } else // Salary paytype: fixed pay for 40 hours { regularPay = emp.PayRate * 40.0; overtimePay = 0.0; } grossPay = regularPay + overtimePay; // Fixed display line with correct values per column string DisplayPayroll = String.Format("{0,-18}{1,14:F2}{2,11:C}{3,13:C}", emp.FirstName + " " + emp.LastName, emp.HoursWorked, // Show actual hours worked, not pay emp.PayRate, // Show actual pay rate, not overtime pay grossPay); listPayroll.Items.Add(DisplayPayroll); }
3. Clean Up Duplicate Header
You’re adding the same header twice in the btnCompute_Click method—remove one of these lines:
// Remove the duplicate line below // listPayroll.Items.Add(DisplayHeader);
4. Add Null Safety for File Reading
If your CSV file only has a header (no employee data), InputRecord could be null when you try to split it, causing another exception. Add a null check in your file reading loop:
while(!inputFile.EndOfStream) { InputRecord = inputFile.ReadLine(); if (InputRecord == null) break; // Add this line to avoid null reference errors InputFields = InputRecord.Split(','); // ... rest of your worker population code }
5. Properly Dispose of StreamReader
Use a using block to automatically clean up the file stream when you’re done, instead of manually calling Close():
// Replace your StreamReader setup with this: using (StreamReader inputFile = File.OpenText(openFileDialog1.FileName)) { InputRecord = inputFile.ReadLine(); // Skip header line while(!inputFile.EndOfStream) { InputRecord = inputFile.ReadLine(); if (InputRecord == null) break; InputFields = InputRecord.Split(','); // ... populate worker and add to EmployeeList } } // No need to call inputFile.Close() anymore—the using block handles disposal
Putting all these fixes together should resolve the exception and make your payroll calculator display accurate results.
内容的提问来源于stack exchange,提问作者PleaseHelp

