【问题标题】:Select the next item in a listbox C#选择列表框中的下一项 C#
【发布时间】:2014-07-24 16:35:37
【问题描述】:

我正在尝试遍历列表框,每次循环选择下一个项目。但是每当我运行应用程序时,它不会转到下一个项目,它只是使用第一个选定的项目。

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;
    } 
}

编辑:删除 Convert.ToInt32

编辑 2:编辑代码以反映更改

编辑 3:正确的代码

【问题讨论】:

  • this: Convert.ToInt32(lb.Items.Count.ToString()) 应该只是 lb.Items.Count
  • 这是什么Convert.ToInt32(lb.Items.Count.ToString())?我猜你喜欢字符串..
  • 这可能已经完成了。我不知道我为什么这样做......嗯......
  • 如果不清楚,您的Convert 呼叫是错误的。您正在使用 ToString() 将整数 (Count) 转换为字符串,只是为了立即使用 Convert.ToInt32 将其转换回整数,这完全没有必要 - 只需直接使用 Items.Count 并删除所有噪音和浪费的 CPU 周期。
  • 也可以把if (countMinusOne.ToString() == lb.SelectedIndex.ToString())简单写成if (countMinusOne == lb.SelectedIndex)

标签: c# winforms for-loop listbox


【解决方案1】:

你的逻辑是错误的。您需要修改循环内的 URL,而不是其上方:

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;
}

【讨论】:

  • 谢谢。这是漫长的没有喝咖啡的日子。
【解决方案2】:

你可以这样做:

对于上一项:

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

下一项:

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

如果你需要详细的,你可以参考这个:

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

希望对你有帮助!

【讨论】:

  • 我试过了,还是没有选择下一项。
猜你喜欢
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
相关资源
最近更新 更多