Reputation: 1794
i need to check if a worksheet exist in excel and if not, to create it. I'm using infragistics and the following code gives me the following error:
use of unassigned local variable 'workSheet'.
this is the code:
Workbook workbook = new Workbook();
Worksheet workSheet;
foreach (Something result in results)
{
foreach (Something item in result.Something)
{
if (!workbook.Worksheets.Exists(item.GetType().Name))
{
workSheet = workbook.Worksheets.Add(item.GetType().Name);
}
// cell font
IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont();
....
}
}
The error is about the: IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont()
on the workSheet variable.
thanks.
Upvotes: 0
Views: 519
Reputation: 4353
Here is how you can avoid the error. Initialize worksheet to null when you declare it. Do not forget the null check before accessing the worksheet.
Workbook workbook = new Workbook();
Worksheet workSheet = null;
foreach (Something result in results)
{
foreach (Something item in result.Something)
{
if (!workbook.Worksheets.Exists(item.GetType().Name))
{
workSheet = workbook.Worksheets.Add(item.GetType().Name);
}
if (workSheet != null)
{
// cell font
IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont();
....
}
....
}
}
Upvotes: 1
Reputation: 1794
I've found the answer:
Worksheet workSheet = null;
if (!workbook.Worksheets.Exists(item.GetType().Name))
{
workSheet = workbook.Worksheets.Add(item.GetType().Name);
}
else
{
workSheet = workbook.Worksheets[item.GetType().Name];
}
// cell font
IWorkbookFont oFont = workSheet.Workbook.CreateNewWorkbookFont();
I had to make sure the workSheet variable has values (initialized).
Upvotes: 0