When I try to find a value that is not saved in excel I can't stop loops and get a message from the MessageBox
killExcel();
OpenFileDialog file = new OpenFileDialog();
string filename = Path.GetFileName(file.FileName);
if (file.ShowDialog() == DialogResult.OK) //if there is a file chosen by the user
{
Boolean chc = false;
var Excel = new Microsoft.Office.Interop.Excel.Application();
//var xlWB = Excel.Workbooks.Open("C:/Users/User/Desktop/ttt.xlsx");
var xlWB = Excel.Workbooks.Open(Path.GetFullPath(file.FileName));
var xlSht = xlWB.Worksheets[1];
Microsoft.Office.Interop.Excel.Range range = xlSht.Columns[1];
Microsoft.Office.Interop.Excel.Range findRange;
object missing = System.Reflection.Missing.Value;
findRange = range.Find(id_v.Text, missing,
Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues,
Microsoft.Office.Interop.Excel.XlLookAt.xlPart,
Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false, missing, missing);
string result = "";
int a = range.Rows.Count;
if (findRange != null)
{
while (chc==false)
{
for (int i = 1; i <= a; i )
{
result = Convert.ToString(xlSht.Cells[i, findRange.Column].Value);
if (result == id_v.Text && result != null)
{
id.Text = result;
chc = true;
break;
}
}
if (chc==false) {
MessageBox.Show("Not found!");
break;
}
}
}
}
Sorry I'm just a beginner in programming and I can't understand why the loop is not stopping when the value is not founded
CodePudding user response:
Your while (chc==false) will always return false if the value is not found keeping it in the infinite loop.
CodePudding user response:
Remove the while(csc=false) loop. The for loop accomplishes what you are trying to do and will exit if it finds the entry without the outer while loop. When the for loop exits, either csc will be true because you set it when the entry was found or csc will be false because you initialized it to false before entering the for loop.