ploxiblox
ploxiblox

Reputation: 67

Select the next item in a listbox C#

I'm trying to loop through a listbox, selecting the next item every loop. But whenever I run the application it doesn't go to the next item, it just uses the first selected item.

lb.SelectedIndex = 0;
for (int i = 0; i < lb.Items.Count; i++)
{
    using (var process = new Process())
    {
        string tn = lb.SelectedItem.ToString();
        string url = "https://enterprisecenter.verizon.com/enterprisesolutions/global/dlink/repairs/iRepair/DelegateDispatch.do?exec=delegateRoute&action=VIEW_BY_NUMBER_VIEW_TKT_SECTION&ticketNumber=" + tn + "&state=";
        process.StartInfo.FileName = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
        process.StartInfo.Arguments = url;
        process.Start();
    }
    if (lb.SelectedIndex < lb.Items.Count - 1)
    {
        lb.SelectedIndex = lb.SelectedIndex + 1;
    } 
}

Edit: Removed Convert.ToInt32

Edit 2: Edited code to reflect changes

Edit 3: Correct Code

Upvotes: 0

Views: 879

Answers (2)

Ken White
Ken White

Reputation: 125757

Your logic is wrong. You need to modify the URL inside your loop, not above it:

lb.SelectedIndex = 0;

for (int i = 0; i < lb.Items.Count; i++)
{
    using (var process = new Process())
    {
        string tn = lb.SelectedItem;
        string url = "privateURL" + tn + "privateURL";
        process.StartInfo.FileName = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
        process.StartInfo.Arguments = url;
        process.Start();
    }
    lb.SelectedIndex := lb.SelectedIndex + 1;
}

Upvotes: 2

Kulasangar
Kulasangar

Reputation: 9454

You could do something like this:

for the previous item:

if (lb.SelectedIndex > 0)
{ 
 lb.SelectedIndex = lb.SelectedIndex - 1; 
}

next item:

if (lb.SelectedIndex < lb.Items.Count - 1)
{
 lb.SelectedIndex = lb.SelectedIndex + 1;
} 

If you need in detail you could refer this:

http://social.msdn.microsoft.com/Forums/vstudio/en-US/92fdb8e2-47c9-49a0-8063-8533b78f41d0/c-listbox-select-nextprevious?forum=csharpgeneral

Hope it helps!

Upvotes: 0

Related Questions