【问题标题】:VB.NET Listbox selectedindexVB.NET Listbox selectedindex
【发布时间】:2012-02-13 18:43:33
【问题描述】:

在我的代码中,我选择 excel 文件将它们添加到列表框中,然后我运行一些代码来替换列表中所有 excel 文件上的某个单元格。每次它更改 excel 文件中的一个单元格时,它都会使用

转到列表框中的下一个单元格
Me.ListBox2.SelectedIndex = Me.ListBox2.SelectedIndex + 1

但是当它到达列表的末尾时,它会给我一个错误。我怎样才能让我的列表框知道它已经结束了。

【问题讨论】:

    标签: vb.net listbox


    【解决方案1】:

    这样检查:

    if Me.ListBox2.SelectedIndex + 1  < Me.ListBox2.items.count then
        Me.ListBox2.SelectedIndex + = 1
    End if
    

    【讨论】:

    • 好像不行,它没有选择下一项,而是停留在第一项。
    • 使用 +=1 将其缩短一点。 ;)
    【解决方案2】:

    我想我会做一个 For/Each/Next 来遍历这样的项目:

    For Each ListItem As Object In ListBox2.Items
    
        'Set Active item as selected
        ListBox2.SelectedItem = ListItem
    
        'manipulate file
        UpdateExcelFile(ListItem.ToString)
    
    Next
    

    【讨论】:

    • 看起来确实像一个更干净的方法,会研究这个。
    【解决方案3】:

    只是为了好玩。您可以在不使用 IF/END IF 的情况下执行此操作
    以下代码会将 selectedindex 移动到下一项,直到到达列表框的末尾。

    ListBox1.SelectedIndex += Math.Abs(CInt(ListBox1.SelectedIndex < ListBox1.Items.Count - 1))
    

    【讨论】:

    • 我不建议使用这种方法。只是发布它以显示替代方法。 ;)
    • 哦,有人不喜欢不可读的单行代码。 ;) 哦,好吧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    相关资源
    最近更新 更多