Looping

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
 
M

Michael Moreno

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Reducing Code 1
Adding to Array 7

Top