Click here to Skip to main content
15,910,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
who can help please?
I have a listbox with some names (datasource is assigned in code)

listbox1
Gery
Tom
Bob
Alisa
Madona
Dreni
Meni
Geni

so how can i use another list or for exampl when I clik in a button that show me only last four members in listbox... that list should be also like MessaggeBox

so in messagge box or another listbox that be only the last four member like:
Gery
Tom
Bob
Alisa

to find first four member I use this code
C#
string msg = string.Empty;
            for (int i = 0; i < 10; i++)
            {
                msg += (string)listBox3.Items[i] + "\n";
            }


how about last four....!

thnx
Posted

That code doesn't make much sense - I can tell you haven't even executed it, because you would get an Index out of range error - you are looping ten times, and have on eight items in your listbox.

You do realize that every Collection has a Count parameter? Which tells you how many items are in the collection? And that string concatenation is very inefficient - you should use a StringBuilder instead?
So to access the last four items:
C#
int itemCount = listbox3.Items.Count;
StringBuilder sb = new StringBuilder();
for (int i = itemCount - 4; i < itemCount; i++)
   {
   sb.AppendFormat("{0}\n", listBox3.Items[i]);
   }
msg = sb.ToString();
 
Share this answer
 
Hi,
Use this
C#
string msg = string.Empty;
int count=0;
for (int i = listbox1.Items.Count-1; i >= 0; i--)
{
    msg += (string)listBox3.Items[i] + "\n";
    count++;
    if(count == 4)
       break;
}


All the best..
 
Share this answer
 
You code possibly finds the first ten (not four).

To access the last four you need something like
C#
int f = listBox3.Items.Count - 4;
if (f < 0 ) f = 0;
for (int i = f; f < listBox3.Items.Count; i++)
{
  msg += (string) listBox3.Items[i] + "\n";
}



BTW listBox3 is a poor name for a variable.
 
Share this answer
 
if you want to display last four items
use
int i = 6; i < 10; i++

or else if you want to display first four use
int i = 0; i < 4; i++
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900