<html>
<head>
<title>Determining Selected Items in a CheckBoxList Control</title>
<link rel="stylesheet" href="/shared/netdemos.css">
<script language="C#" runat="server">
int [ ] opts = {0,1,1,0,0,1,0,0,1,1};
int nCorrect=5;
int i, nRight, nWrong;
string msg;
void Page_Load ( object src, EventArgs e ) {
// initialize counter
if ( !IsPostBack ) ViewState [ "nTries" ] = 0;
}
void chkChoices ( object src, EventArgs e ) {
// increment counter
ViewState [ "nTries" ] = ( int ) ViewState [ "nTries" ] + 1;
// get selected items and check if right
foreach ( ListItem item in choices.Items ) {
if ( item.Selected && opts [ i ] == 1 ) nRight++;
if ( item.Selected && opts [ i ] == 0 ) nWrong++;
i ++;
}
// determine score and display appropriate message
if ( ( nRight < nCorrect ) || ( nWrong > 0 ) ) {
if ( nRight < 1 )
msg = "You have no correct answer.";
else
msg = "You have " + nRight + " correct and " + nWrong + " incorrect answers.";
}
else if ( ( nRight==nCorrect ) && ( nWrong==0 ) ) {
int nTries = ( int ) ViewState [ "nTries" ];
if ( nTries == 1 )
msg = "Bravo! You got them all on the first try!";
else {
string grade = nTries < 5 ? "Not bad." : "Not so good.";
msg = grade + " It took you " + nTries + " tries to get it right.";
}
}
message.Text = msg;
}
void reSet ( object src, EventArgs e ) {
// clear selection
choices.SelectedIndex = -1;
// reset counter
ViewState [ "nTries" ] = 0;
// clear message
message.Text = "";
}
</script>
</head>
<body>
<!-- #include virtual="~/shared/top.inc -->
<div class="header"><h2>Determining Selected Items in a CheckBoxList Control</h2></div>
<!-- #include virtual="~/shared/viewsrc_top.inc" -->
<hr size=1 width=92%>
<center>
<form runat="server">
<h2>Select the inventions that were created before 1500 A.D.</h2>
<p class="small">HINT: There are 5</p>
<table cellpadding=20 bgcolor="beige" border>
<tr align="center"><td>
<asp:checkboxlist id="choices" repeatcolumns=2 runat="server">
<asp:listitem text="F-16 Falcon ( vehicle )" />
<asp:listitem text="Stirrups ( tool )" />
<asp:listitem text="Crop Rotation ( science )" />
<asp:listitem text="Gravity" />
<asp:listitem text="Wheellock Musket ( weapon )" />
<asp:listitem text="Flintlock Musket ( weapon )" />
<asp:listitem text="M-1 Rifle ( weapon )" />
<asp:listitem text="Heliocentric concept ( science )" />
<asp:listitem text="Scissors ( tool )" />
<asp:listitem text="Gunpowder ( tool/weapon )" />
</asp:checkboxlist>
</td></tr>
<tr align="center"><td>
<p><asp:button text="Submit" onClick="chkChoices" runat="server" />
<asp:button text="Reset" onClick="reSet" runat="server" /></p>
</td></tr>
</table>
<p><b><asp:label id="message" runat="server" /></b></p>
</form>
</center>
<hr size=1 width=92%>
<!-- #include virtual="~/shared/viewsrc.inc" -->
</body>
</html>