Looping

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi I have the following code:

if (chkMaster.Checked)
{
dbFile = dbFile.Substring(0,dbFile.LastIndexOf(@"\")+1) + "master.mdb";
compactDatabase(ref testPassword, dbFile, userID, pword, regPath, systemFile);
if (!testPassword)
{
return;
}
progressBar.Value ++ ;
}

if (chkToolbox.Checked)
{
dbFile = dbFile.Substring(0,dbFile.LastIndexOf(@"\")+1) + "toolbox.mdb";
compactDatabase(ref testPassword, dbFile, userID, pword, regPath, systemFile);
if (!testPassword)
{
return;
}
progressBar.Value ++ ;
}

if (chkImport.Checked)
{
dbFile = dbFile.Substring(0,dbFile.LastIndexOf(@"\")+1) + "Import.mdb";
compactDatabase(ref testPassword, dbFile, userID, pword, regPath, systemFile);
if (!testPassword)
{
return;
}
progressBar.Value ++ ;
}

if (chkUser.Checked)
{
dbFile = dbFile.Substring(0,dbFile.LastIndexOf(@"\")+1) + "User.mdb";
compactDatabase(ref testPassword, dbFile, userID, pword, regPath, systemFile);
if (!testPassword)
{
return;
}
progressBar.Value ++ ;
}

if (chkImpData.Checked)
{
dbFile = dbFile.Substring(0,dbFile.LastIndexOf(@"\")+1) + "ImpData.mdb";
compactDatabase(ref testPassword, dbFile, userID, pword, regPath, systemFile);
if (!testPassword)
{
return;
}
progressBar.Value ++ ;
}


As can be seen the code is quite repetitive, is there some way to reduce
this code by maybe calling a method? CheckBoxes are checked to select which
database to compact. Would it be better to loop throught these somehow rather
than using all the if statements?

Thanks
 
Something like this would already simplify it a lot:

private void CompactDB(string dbFileName)
{
// NEED to check what dbFile is, where it is declared, etc

dbFile = dbFile.Substring(0,dbFile.LastIndexOf(@"\")+1) +
dbFileName;

compactDatabase(ref testPassword, dbFile, userID, pword, regPath,
systemFile);

if (!testPassword)
return;

progressBar.Value++;
}

....
if (chkMaster.Checked)
CompactDB("master.mdb");

if (chkToolbox.Checked)
CompactDB("toolbox.mdb");

if (chkImport.Checked)
CompactDB("Import.mdb");

if (chkUser.Checked)
CompactDB("User.mdb");

if (chkImpData.Checked)
CompactDB("ImpData.mdb");

Now you can of course use a checklist box to put all the checkboxes in
it and loop through it. That would be even better!
 
Back
Top