Ch 11 Pg459 Exercise 5 C#
I'm trying to search through a sorted list to find an item that is entered into a textbox. However, when I try to add an else statement to the Find() method such as:
void Find(object sender, EventArgs e)
{
foreach(DictionaryEntry Item in mySortedList)
{
if(findBox.Text == Item.Key.ToString())
{
findLbl.Text = "You have found " + "<b>" + Item.Key.ToString() + ".</b><br/>";
findLbl.Text +="<b> Definition: </b>" + Item.Value.ToString();
}
else
{
findLbl.Text = "That item is not in the List";
}
}
}
It doesn't find anything except for the last item in the list, which in this case is Zebra, but it works fine when the else statement is not in there. Can anyone explain to me why this is?
//***Code***//
<%@ Page Language="c#" %>
<html>
<script runat="server">
SortedList mySortedList = new SortedList();
void Page_Load(object source, EventArgs e)
{
mySortedList["armadillo"]="any of a family ... small bony plates";
mySortedList["amaryllis"]="an autumn-flowering ... Sprekelia)";
mySortedList["zebra"]="any of several fleet ... white or buff";
mySortedList["artichoke"]="a tall composite herb ... cooked as a vegetable";
mySortedList["aardvark"]="a large burrowing ... termites and ants";
}
void Find(object sender, EventArgs e)
{
foreach(DictionaryEntry Item in mySortedList)
{
if(findBox.Text == Item.Key.ToString())
{
findLbl.Text = "You have found " + "<b>" + Item.Key.ToString() + ".</b><br/>";
findLbl.Text +="<b> Definition: </b>" + Item.Value.ToString();
}
}
}
void Display(object sender, EventArgs e)
{
findLbl.Text = "";
foreach(DictionaryEntry Item in mySortedList)
{
findLbl.Text += Item.Key.ToString() + " " + Item.Value.ToString() + "<br/>";
}
}
</script>
<h1>What are you looking for?</h1>
<form runat="server" autopostback="true">
<asp:TextBox id="findBox" runat="server"/>
<br/><br/>
<asp:button id="find" Text="Search" OnClick="Find" runat="server"/>
<asp:button id="display" Text="Display List" OnClick="Display" runat="server"/>
<br/><br/>
<asp:label id="findLbl" runat="server"/>
</form>
</html>
|