I have this issue where no matter what method i try, i cannot update a variable on each iteration of the for loop so that i can show the user the current status in a percentage of the loop. Heres my method:
void startOperation()
{
Console.WriteLine("Beginning start operations..." + searchText);
Console.WriteLine("Opening Workbook: " + filePath);
// create excel-instance:
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
// open the concrete file:
Workbook xlWorkbook = xlApp.Workbooks.Open(@filePath);
//MessageBox.Show(filePath);
// select worksheet. NOT zero-based!!:
_Worksheet xlWorksheet = xlWorkbook.Sheets[1];
//MessageBox.Show(Convert.ToString(xlWorksheet.Name));
Microsoft.Office.Interop.Excel.Range range;
int numRows = xlWorksheet.UsedRange.Rows.Count;
currRow = 1;
numRowsDeleted = 0;
nullCounter = 0;
decimal percentageComp;
//Parallel.For(1, numRows, new ParallelOptions { MaxDegreeOfParallelism = 1 }, i =>
for (int i = 1; i < numRows; i++)
{
percentageComp = currRow / numRows * 100;
Console.Clear();
Console.WriteLine("Number of Rows: " + numRows);
Console.WriteLine("Checking Row #: " + currRow);
Console.WriteLine("Number of Rows Deleted: " + numRowsDeleted);
Console.WriteLine("Percentage Complete: " + percentageComp);
if (i > 1)
{
i -= 1;
}
//Create Worksheet Range
range = (Microsoft.Office.Interop.Excel.Range)xlWorksheet.Cells[i, 2];
//MessageBox.Show(cellValue);
if (nullCounter == nullCount) //was 5, decreased to 3, then changed to nullCount variable
{
closeOperation(xlApp, xlWorkbook);
break;
}
if (Convert.ToString(range.Value) != null) //if (cellValue != null || cellValue != "")
{
cellValue = Convert.ToString(range.Value);
nullCounter = 0;
if (cellValue.Contains(searchText))
{
//MessageBox.Show("Found a row that needs deleting!");
//range.Rows[i].Delete(XlDeleteShiftDirection.xlShiftUp);
//Thread.Sleep(5);
xlWorksheet.Rows[i].Delete(XlDeleteShiftDirection.xlShiftUp);
//((Range)xlWorksheet.Rows[i]).Delete(XlDeleteShiftDirection.xlShiftUp);
numRowsDeleted++;
//nullCounter = 0;
i--;
currRow++;
}
else
{
currRow++;
//percentageComp = currRow / numRows * 100;
//nullCounter = 0;
}
}
else
{
//MessageBox.Show("Null cell value");
nullCounter++;
}
i++;
}
//);
}
No matter what i try, my console output only shows 0. Im confused as to what i might be doing wrong here so any help is appreciated. Thanks for your time!
currRow
is an integer, and so is numRows
. curRow
is less than numRows
.
The result of integer division is an integer. 40 / 100
is less than one. The only integer value less than one is zero. For any integers x
and ``y, where x
is less than y
, x / y
is less than one -- which will truncate to zero.
Once you've got zero, you can multiply zero by any number you like -- it's still zero.
So don't use integer division. Cast them to decimal
.
percentageComp = ((decimal)currRow / (decimal)numRows) * 100;
The guys in comments found a bunch of other bugs, take a look at those too.