in my Windows Forms app I keep getting an unhandled ArgumentException ("input array is longer than number of columns in table") in line 56 (within catch). For debugging purposes I'm trying to show a message box, but I always get the exception and the message box never shows.
In the watch window it says "value not available at current pointer".
How can I print simple debugging information in Windows Forms apps, just like I would do in console apps?
P.S. The method below is run after a button is clicked in the forms app.
using System;
using System.Data;
using System.IO;
using System.Text;
using CsvHelper;
using System.Windows.Forms;
namespace ARautomat_visual {
class Model {
// read CSV-file to DataTable
// hasHeader is passed as FALSE
public static DataTable GetDataTableFromCsv (string file, bool hasHeader = true) {
DataTable dataTable = new DataTable();
using (TextReader infile = new StreamReader(file, Encoding.Default))
using (CsvParser csv = new CsvParser(infile)) {
csv.Configuration.Delimiter = ";";
bool datevFormat = false;
string[] row;
for (int i = 0; (row = csv.Read()) != null; i++) {
if (i == 0) {
if (datevFormat == false && (row[0] == "EXTF" || row[0] == "DTVF")) {
datevFormat = true;
i--;
}
else if (hasHeader == true) {
try {
string errMsg = $"row.Length: {row.Length}\n";
foreach (DataColumn item in dataTable.Columns) {
errMsg += $"{item.ColumnName}, ";
}
Program.TriggerError(errMsg);
for (int j = 0; j < row.Length; j++) {
dataTable.Columns.Add(row[j]);
}
}
catch (Exception e) {
string errMsg = $"Fehler: {e.Message}; row.Length: {row.Length.ToString()}; Columns: {dataTable.Columns.ToString()}";
MessageBox.Show("Mist!");
Program.TriggerError(errMsg);
throw; // this is line 56
}
}
else {
dataTable.Rows.Add(row);
}
}
else if (i > 0) {
dataTable.Rows.Add(row);
}
}
}
return dataTable;
}
}
}
Program.cs
static class Program {
// print all warnings
public static void PrintWarnings() {
if (!String.IsNullOrEmpty(warningsTriggered)) {
TriggerStatus(warningsTriggered, "Warnung");
}
}
// print warnings, print errors, exit
public static void TriggerError (string msg) {
PrintWarnings();
TriggerStatus("Fehler: " + msg + @"Programm wird nach Klick auf 'OK' beendet.", "Fehler");
//Application.Exit();
Form.ActiveForm.Close();
}
}
Turns out the problem was within the else
-clause: I tried to add a new row to the empty dataTable
without creating columns in beforehand.
I added the for
-loop below and now the code runs fine.
else {
for (int j = 1; j <= row.Length; j++) {
dataTable.Columns.Add("Column " + j);
}
dataTable.Rows.Add(row);
}
What did confuse me a lot was the fact that Visual Studio was actually placing the exception symbol at the end of the catch
-block, despite the fact that the else if
-block wasn't even entered and the exception was actually thrown in the else
-block.
Thanks to Chetan and PaulF for guiding me with debugging using break points!!