So I have this code for a window:
public partial class List : Window
{
DataTable table = null;
ExcelWorksheet ws = null;
string user = System.Environment.UserName;
public void Initialize()
{
string path = "Log.xlsx";
FileInfo file = new FileInfo(path);
try
{
if (File.Exists(path))
{
using (ExcelPackage pack = new ExcelPackage(file))
{
bool sheetfound = false;
//runs through each sheet to find a specific one
foreach (ExcelWorksheet sheet in pack.Workbook.Worksheets)
{
if (sheet.Name.Equals(user))
{
sheetfound = true;
ws = pack.Workbook.Worksheets[user];
break;
}
}
//Creates new sheet if it hasn't found the specific one
if (!(sheetfound))
{
ws = MainWindow.Create_Worksheet(pack);
pack.Save();
}
}
}
else
{
using (ExcelPackage pack = new ExcelPackage(file))
{
ExcelWorksheet ws = MainWindow.Create_Worksheet(pack);
pack.Save();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Exception caught:\n\n" + ex as string, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
fUpdate(new Object, new RoutedEventArgs);
}
public void fUpdate(object sender, RoutedEventArgs e)
{
table.Rows.Clear();
MessageBox.Show(ws.Dimension.End.Row.ToString());
}
}
and this one from the main window:
public partial class MainWindow : Window
{
public static ExcelWorksheet Create_Worksheet(ExcelPackage pack)
{
ExcelWorksheet ws = pack.Workbook.Worksheets.Add(System.Environment.UserName);
ws.Cells[1, 1].Value = "Date";
ws.Cells[1, 2].Value = "Time";
ws.View.FreezePanes(2, 1);
return ws;
}
}
What this is supposed to do right now is, when the second window launches, it sets the Excel file and worksheet. I used Quickwatch to see if it works and it does work, ws gets set to the specific sheet that I wanted and ws.Dimension.End.Row
returns 1. However, after it gets out of the try-catch part (once it reaches fUpdate), ws.Dimension.End.Row
suddenly throws a NullReferenceException. I checked and ws is still the same ExcelWorksheet object and it didn't go through anything (that I know of) that would change its value. What causes this error? Thanks!
(ws
returns the ExcelWorksheet object but ws.Dimensions
return the exception)