I am working with lists. I have been able to determine the first and last position of items in my list. I am using getPostion and displaying item name through a Label. Three buttons in my form: ShowFirstItem ShowNextItem(not working) and ShowLastItem show the corresponding item in a label. I am having problems for my next item. I don’t have a member that is holding the current fruit_tree. So I am not sure how to either add an int member or another fruit_tree member called current. How would I be able to find out next (item after first) and display result?
public class ListForTrees
{
public fruit_trees GetNextTree()
{
current = 0;
fruit_trees ft = first_tree;
int i = 0;
while (i != current)
{
ft = ft.next_tree;
i++;
}
return ft;
}
}
ListForTrees mainlist = new ListForTrees();
private void BtnGo_Click(object sender, EventArgs e)
{
fruit_trees[] ar_items = { new fruit_trees("cherry", 48, 12.95, 3),
new fruit_trees("pine", 36, 9.95, 8),
new fruit_trees("oak", 60, 14.95, 2),
new fruit_trees("peach", 54, 19.95, 3),
new fruit_trees("pear", 36, 11.85, 2),
new fruit_trees("apple", 62, 13.45, 5)
};
mainlist = new ListForTrees(ar_items);
fruit_trees current = mainlist.first_tree;
while (current != null)
{
TxtOutput.AppendText(current.ToString() + Environment.NewLine);
current = current.next_tree;
}
}
private void ShowFirstItem_Click_1(object sender, EventArgs e)
{
// Show First Item
labelSpecificTree.Text = mainlist.first_tree.GetTreeType;
}
private void ShowLastItem_Click(object sender, EventArgs e)
{
//Show Last Item
labelSpecificTree.Text = mainlist.last_tree.GetTreeType;
}
private void ShowNextItem_Click(object sender, EventArgs e)
{
//Show Next Item
fruit_trees obj = mainlist.GetNextTree();
if (obj == null)
{
labelSpecificTree.Text = "No more trees!";
}
else
{
mainlist.current++;
labelSpecificTree.Text = obj.next_tree.GetTreeType.ToString();
}
}
}
I would add
to the listoftrees. in the constructor set it to 0;
Then create a method to return the current fruit_trees object
now this method returns the current and not the next object. So you have 2 options in the next button event.
the quesiton here is do you want to move to the next tree object every time the button is clicked?
if so increment the current property and then call getcurrent to display. If you want the current to be retained and not move (i.e. clicking next over and over will result in the same thing)
then display getcurrent().next_tree.tree_type with no increment to current.