Reputation: 75
I'm trying to implement a previous and next buttons.
I have a list of string called list1 which is filled with whatever is a user has inputted from a textbox. I can't access the previous (not the last) string in the list. IndexOf method isn't useful as I don't know what user will input.
private void previousBtn_click(object sender, EventArgs e)
{
getList();
int min = 0;
int max = list1.Count;
if(max==min)
{
previousBtn.Visible = false;
}
else
{
int temp =list.Count-1;
//how do I get my string if I know the element index from the previous line?
//textbox1.Text = thatPreviousString;
}
}
Sorry, it should be easy but I can't figure it out. How can I actully get my previous string in the list if the value is kind of unknown to me, so I can't just use find() and indexOf. MSDN shows that there is a property called Item but there is no proper tutorial or code bit that shows how to use it.
UPDATE: Let's say the user has typed "www.google.com", "www.facebook.com", "twitter.com" and then "www.yahoo.com". This urls are saved in list1. The last one was "www.yahoo.com", I can get it by calling Last(). The user can press the previous button anytime, so I can't specify the number of elements in list1, it's growing dynamically. I can only get the number of elements by calling
list1.Count and the last index by calling list1[list1.Count-1]
Now I know the number of indexes and elements, so how do I get the previous string, e.g. "www.twitter.com", if I can only say I can give you the index, give my string back?
By the way, ElementAs is only for arrays, doesn't work for lists.
Upvotes: 0
Views: 1808
Reputation: 43264
string temp =list[list.Count-1];
will give you the last element in the list.
string temp =list[list.Count-2];
will give you the previous element.
Remember, lists are 0-indexed, ie the first element is accessed via [0]
, so the last element will be [list size - 1]
.
So in your case textbox1.Text = list[list.Count-2];
will write the previous string into the textbox.
However, that won't give you a proper previous functionality. Pressing previous again won't give you list[list.Count-3]
. You could though have a currentIndex
variable that you decrement whenever previous is pressed for example and do textbox1.Text = list[currentIndex]
.
Upvotes: 0
Reputation: 54801
how do I get my string if I know the element index from the previous line?
int prevIndex; // element index from the previous line that you know
string temp = list1[prevIndex - 1];
Upvotes: 3