0
votes

I'm trying to handle the exception when Worksheet is not present using this code:

int k = blYear.SelectedIndex;
ExcelWorksheet currentWorkSheet;

try
{
    currentWorkSheet = workbook.Worksheets[k + 1];
}
catch (Exception)
{
    MessageBox.Show("La hoja de trabajo no existe en el archivo de Excel", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
    btnCargarExcel.Enabled = true;
    blYear.Enabled = true;
    filePath.Text = "";
}

But I'm getting this errors:

  • if I try to compile this error appears

    Error 1 Use of unassigned local variable 'currentWorkSheet' d:\Work\ClanMovil\CMApp\WindowsFormsApplication1\WindowsFormsApplication1\ExcelDBUserControl.cs 71 46 CMApp

  • if I omit the error and continue building then I get this other

--------------------------- Microsoft Visual Studio --------------------------- Source file: D:\Work\ClanMovil\CMApp\WindowsFormsApplication1\WindowsFormsApplication1\ExcelDBUserControl.cs

Module: d:\Work\ClanMovil\CMApp\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\CMApp.exe

Process: [4944] CMApp.vshost.exe

The source file is different from when the module was built. Would you like the debugger to use it anyway? Yes No

System.Collections.Generic.KeyNotFoundException was unhandled
HResult=-2146232969 Message=The given key was not present in the dictionary. Source=mscorlib StackTrace: at System.Collections.Generic.Dictionary`2.get_Item(TKey key) at OfficeOpenXml.ExcelWorksheets.get_Item(Int32 PositionID) at WindowsFormsApplication1.ExcelDBUserControl.btnCargarExcel_Click(Object sender, EventArgs e) in d:\Work\ClanMovil\CMApp\WindowsFormsApplication1\WindowsFormsApplication1\ExcelDBUserControl.cs:line 66 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at WindowsFormsApplication1.Program.Main() in d:\Work\ClanMovil\CMApp\WindowsFormsApplication1\WindowsFormsApplication1\Program.cs:line 20 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

what's the proper way to handle this?

EDIT for 1st error Ok, seeing the error about the undeclared var I made some modifications to my code and now is this:

using (var package = new ExcelPackage(existingFile))
{
    ExcelWorkbook workbook = package.Workbook;
    ExcelWorksheet currentWorkSheet = workbook.Worksheets.First();

    if (workbook != null)
    {
        if (workbook.Worksheets.Count > 0)
        {

            int k = blYear.SelectedIndex;

            try
            {
                currentWorkSheet = workbook.Worksheets[k + 1];
            }
            catch (Exception)
            {
                MessageBox.Show("La hoja de trabajo no existe en el archivo de Excel", "Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
                btnCargarExcel.Enabled = true;
                blYear.Enabled = true;
                filePath.Text = "";
            }

        }
    }
}

But this has a problem, even if Exception is launched the first worksheet is loaded because of this ExcelWorksheet currentWorkSheet = workbook.Worksheets.First(); and this is not what I want to achieve. If I define the var as ExcelWorksheet currentWorkSheet; and set the value inside the first condition then the same error:

Error 1 Use of unassigned local variable 'currentWorkSheet' d:\Work\ClanMovil\CMApp\WindowsFormsApplication1\WindowsFormsApplication1\ExcelDBUserControl.cs 71 46 CMApp

appears so I don't know how to handle this, I'm stucked here

1
Where is the Instance of the WorkBook, or Excel Application? try looking at this link for a simple fix. stackoverflow.com/questions/1111935/c-sharp-and-excel-interopMethodMan
@DJKRAZE I made some edit to my post and no, the link you leave me doesn't helpReynier
Does ExcelWorksheet currentWorksheet = null work?Hjalmar Z
@HjalmarZ yes, it does the jobReynier

1 Answers

1
votes

Your updated code is much better. Essentially you need to decide from a business logic/UI behaviour what you want to happen when there isn't a current worksheet. You could set currentWorksheet = null in the exception handler (or before the try) and then add extra logic outside the catch to do... whatever you want to do if currentWorksheet is null. Or just put a return statement in the catch so none of the following code is executed. It's up to you.