Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

Responding to Other Menu Requests

The other two menu events require quite simple code:

private void mnuGradeQuiz_Click(object sender, System.EventArgs e) {

gradeTest();

} // end gradeTest

private void mnuExit_Click(object sender, System.EventArgs e) {

this.Close(); } // end mnuExit

The Grade Quiz menu calls the gradeTest() method, and the Exit menu closes the current form.

Writing the Editor Form

The editor form was designed to be parallel to the quiz form in its general structure. The editor’s main purpose is to allow the user to generate new quizzes, rather than to display existing quizzes. For this reason, the editor uses many features described in the XML Creator program to create new documents and nodes and populate these nodes with values from the form.

Designing the Visual Interface

Figure 10.20 shows the editor’s visual interface. I tried to keep the visual interface as similar to the quiz form as possible, but I used text boxes for user input. The editor has four radio buttons (named optAoptD), but I sized the radio buttons so that their text attributes would not be visible. I carefully placed the text boxes where the radio buttons’ text would normally go. This gives the effect of an editable radio button. The buttons and label at the bottom of the form are just like those in the quiz form. The program has two menus containing elements to load and store the quiz, create a new quiz, add a new question, and close the editor.

310

Figure 10.20: The editor form relies on text boxes to display and retrieve the problems.

Creating the Instance Variables

The instance variables for the editor are typical for the programs in this chapter:

private XmlDocument doc; private XmlNode theTest; private int qNum = 0;

private int numQuestions = 0;

The doc variable will hold the entire quiz document, and theTest will hold a reference to the test. qNum is the current question number, and numQuestions holds the total number of questions in the quiz.

Initializing in the Load Event

The form’s load event loads a sample test to ensure that an XML document is always in memory. As in the quiz program, this eliminates the need for certain kinds of error checking, and the user is free to modify the default quiz, load another quiz, or create a new one.

private void frmEdit_Load(object sender, System.EventArgs e) {

//load up a sample test. doc = new XmlDocument(); doc.Load("sampleTest.qml"); resetQuiz();

} // end frmEdit_Load

The frmEdit_Load() method simply loads up a default document and calls the resetQuiz() method (described in the next section) to start the quiz editing process.

Trick Because I’m using a specific style of XML markup, I decided to give it its own extension (qml for quiz markup language). You commonly do this when you’re working with a specific document structure. You use the more generic xml extension when the exact structure of the document isn’t as important (as in the XML Viewer program, which was designed to handle any XML document).

Resetting the Quiz

Resetting the quiz works exactly the same way in the editor as in the quiz program:

private void resetQuiz(){ theTest = doc.ChildNodes[1];

numQuestions = theTest.ChildNodes.Count; qNum = 0;

showQuestion(0); } // end resetQuiz

The test is retrieved from doc.ChildNodes[1], and numQuestions extracts the number of questions from the test object.

I reset qNum to 0 and showed the initial question using the showQuestion() method.

311

Showing a Question

Showing a question in the editor is much like showing it in the quiz program, except that the radio button values are extracted from the XML document in the editor, rather than in the response array in the quiz program:

private void showQuestion(int qNum){

XmlNode theProblem = theTest.ChildNodes[qNum]; txtQuestion.Text = theProblem["question"].InnerText; txtA.Text = theProblem["answerA"].InnerText; txtB.Text = theProblem["answerB"].InnerText; txtC.Text = theProblem["answerC"].InnerText; txtD.Text = theProblem["answerD"].InnerText; lblNum.Text = Convert.ToString(qNum);

//uncheck all the option buttons optA.Checked = false; optB.Checked = false; optC.Checked = false; optD.Checked = false;

//Check the appropriate option button switch (theProblem["correct"].InnerText){

case "A":

optA.Checked = true; break;

case "B":

optB.Checked = true; break;

case "C":

optC.Checked = true; break;

case "D":

optD.Checked = true; break;

default:

// do nothing break;

} // end switch

}// end showQuestion

The radio buttons are set by extracting the correct element from the current problem and setting the Checked property of the corresponding radio button.

Updating a Question

Whenever the user moves to a new question, the program stores the current question’s data to the internal XML structure by copying the values of the appropriate text boxes to the current problem node:

private void updateQuestion(int qNum){ // updates the current question's XML

XmlNode theProblem = theTest.ChildNodes[qNum]; theProblem["question"].InnerText = txtQuestion.Text; theProblem["answerA"].InnerText = txtA.Text; theProblem["answerB"].InnerText = txtB.Text; theProblem["answerC"].InnerText = txtC.Text; theProblem["answerD"].InnerText = txtD.Text;

//store the correct answer based on the option buttons

312

if (optA.Checked){ theProblem["correct"].InnerText = "A";

}else if (optB.Checked){ theProblem["correct"].InnerText = "B";

}else if (optC.Checked){ theProblem["correct"].InnerText = "C";

}else if (optD.Checked){ theProblem["correct"].InnerText = "D";

}else { theProblem["correct"].InnerText = "X";

}// end if

}// end updateQuestion

The correct value cannot be directly determined from a text box entry, so it is generated by evaluating which radio button has been checked.

Trick It might seem that the correct and response elements are a pain to work with compared to the other elements. True, the radio buttons require more attention than the text elements. This effort is worth it in the long run, however. Most of the elements in a problem are simply text and don’t require any error checking. If you let the user type in an answer, it would be easier to copy the values to and from the resulting text box, but you would have to do all kinds of validation. You would have to ensure that the user typed a legal response, used the correct case, and didn’t try to type the entire answer instead of the letter corresponding to the answer. The overhead associated with using radio buttons for input is offset by the knowledge that the user input will always fall within a predictable range.

Moving to the Preceding Question

Moving to the preceding question works almost exactly the same in the editor and the quiz program. The only new wrinkle is that the editor does not allow the user to move on without clicking one of the option buttons. This ensures that every question will have a response. Otherwise, the quiz could have questions that would be impossible to answer. The noResponse() method (described in the next section) returns the boolean value true if there are no responses and false if at least one of the check boxes has been selected. If no responses are selected, the code reminds the user that something must be selected. If a radio button has been selected, the code proceeds to update the current question, decrement the question number, check to ensure that the question number isn’t less than 0, and display the new question.

private void btnPrev_Click(object sender, System.EventArgs e) {

if (noResponse()){

MessageBox.Show("You must select one of the answers");

}else { updateQuestion(qNum); qNum−−;

if (qNum < 0){ qNum = 0;

MessageBox.Show("First question");

}else { showQuestion(qNum);

}// end 'first question' if

}// end answerEmpty if

}// end btnPrev

313

Moving to the Next Question

The next question code is similar to the preceding question code. However, when the user reaches the last question in the editor, the code prompts to see whether the user wants to add a new question. In an editor, it’s possible that the user will want to add a new question at the end of the quiz.

private void btnNext_Click(object sender, System.EventArgs e) {

if (answerEmpty()){

MessageBox.Show("You must select one of the answers");

}else { updateQuestion(qNum); qNum++;

if (qNum >= numQuestions){ qNum = numQuestions −1;

if (MessageBox.Show("Last question. Add new question?", "last question",

MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes){

mnuAddQuestion_Click(sender, e); } // end 'add question' if

}else { showQuestion(qNum);

}// end 'last question' if

}// end 'answer empty' if

}// end btnNext

Checking for a No Response

The btnNext and btnPrev events need to know whether the option buttons are empty (that is, none of the responses have been checked). This is done by setting a boolean variable named responseEmpty to true. Then I checked each option button to see whether it was checked. If so, responseEmpty is set to false. I then returned the value of responseEmpty. If any radio button has been selected, the noResponse() method returns a value of false. If none of the radio buttons have been selected, noResponse() returns the value true.

private bool noResponse(){

//checks to see if all the check boxes are empty bool responseEmpty = true;

if (optA.Checked){ responseEmpty = false;

} // end if

if (optB.Checked){ responseEmpty = false;

} // end if

if (optC.Checked){ responseEmpty = false;

} // end if

if (optD.Checked){ responseEmpty = false;

} // end if

return responseEmpty; }// end noResponse

314

Saving a File

Saving the file is a simple affair:

private void mnuSaveAs_Click(object sender, System.EventArgs e) {

if (saver.ShowDialog() != DialogResult.Cancel){ doc.Save(saver.FileName);

} // end if

}// end mnuSave

I show a File Save dialog box and use it to get the user’s requested file name. I then call the doc object’s Save() method to save the current XmlDocument to the file system.

Opening a File

Opening a file also uses a familiar method of XmlDocument. I used another File dialog to let the user choose a file to open. Next, I used the Load() method of doc to load the file into memory. I then called the resetQuiz() method to prepare the quiz for editing.

private void menuOpen_Click(object sender, System.EventArgs e) {

if (opener.ShowDialog() != DialogResult.Cancel){ doc.Load(opener.FileName);

theTest = doc.ChildNodes[1]; resetQuiz();

} // end if

}// end mnuOpen

Adding a Question

To add a question to the end of the quiz, I used the algorithm described in the XML Creator program described earlier in this chapter:

private void mnuAddQuestion_Click(object sender, System.EventArgs e) {

numQuestions++;

qNum = numQuestions −1;

//create the new Node

XmlNode newProblem = theTest.ChildNodes[0].Clone(); theTest.AppendChild(newProblem);

showQuestion(qNum);

//clear the screen txtQuestion.Text = ""; txtA.Text = ""; txtB.Text = ""; txtC.Text = ""; txtD.Text = ""; optA.Checked = false; optB.Checked = false; optC.Checked = false; optD.Checked = false;

} // end mnuAdd

315

The mnuAddQuestion_Click() method begins by making a clone of the first problem and then appending the clone to the end of the test. I incremented numQuestions to indicate that the total number of questions has changed, and I set qNum to indicate the last question, which is the new node that has just been created.

I didn’t bother to change the values of the new node (they will still be exactly the same as the values of the first problem node) because it isn’t necessary to do so. I will clear the screen, and when the user moves off this question, the values on the screen will be copied over to the new node with the updateQuestion() method.

Creating a New Test

Creating a new test uses another algorithm developed in the XML Creator program from earlier in the chapter. I modified the code to reflect the structure of the quiz markup language I had devised:

private void mnuNewTest_Click(object sender, System.EventArgs e) {

doc = new XmlDocument();

theTest = doc.CreateNode(XmlNodeType.Element, "test", null);

//create the first line:

//<?xml version="1.0" encoding="utf−8"?>

XmlNode header = doc.CreateXmlDeclaration("1.0", "utf−8", null);

XmlNode theProblem = doc.CreateElement("problem");

XmlNode theQuestion = doc.CreateElement("question");

XmlNode theAnswerA = doc.CreateElement("answerA");

XmlNode theAnswerB = doc.CreateElement("answerB");

XmlNode theAnswerC = doc.CreateElement("answerC");

XmlNode theAnswerD = doc.CreateElement("answerD");

XmlNode theCorrect = doc.CreateElement("correct");

//construct the new node structure doc.AppendChild(header); doc.AppendChild(theTest); theTest.AppendChild(theProblem); theProblem.AppendChild(theQuestion); theProblem.AppendChild(theAnswerA); theProblem.AppendChild(theAnswerB); theProblem.AppendChild(theAnswerC); theProblem.AppendChild(theAnswerD); theProblem.AppendChild(theCorrect);

//populate values of nodes theQuestion.InnerText = "question"; theAnswerA.InnerText = "a"; theAnswerB.InnerText = "b"; theAnswerC.InnerText = "c"; theAnswerD.InnerText = "d"; theCorrect.InnerText = "X";

qNum = 0; showQuestion(0);

} // end mnuNewTest

First, I created a new XmlDocument and XmlNode to hold the document and the test, respectively. I then created the XML header with a call to the XmlDocument’s CreateXmlDeclaration() method.

316

Соседние файлы в предмете Программирование на C++