首页 > 解决方案 > 用两个变量编辑 20 个列表框

问题描述

所以我有 20 个列表框(从 1 到 20),我想对它们执行相同的操作,在这段代码中你会看到listbox1

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    SelectedProfile3.SelectedIndex = 1
    ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1

    While (ListBox1.SelectedItem.Length < SelectedProfile3.SelectedItem) And SelectedProfile3.SelectedIndex = 1

        ListBox1.Items(ListBox1.SelectedIndex) = ListBox1.SelectedItem + (" ")
    End While
    Button4.PerformClick()
End Sub

将会listbox2改变的事情是:

  1. SelectedProfile3.SelectedIndex = 2
  2. 使用listbox2代替listbox1

其余的列表框依此类推

标签: vb.net

解决方案


只需设置列表框名称或键入代码块(单独的主题以在执行时调用)。

正如我所看到的,您在编写时正在使用整数和字符串进行 while 循环(ListBox1.SelectedItem.Length (double data type) < SelectedProfile3.SelectedItem (string type) )

它可能会减少运行时的正确功能或错误。虽然我知道您只能在该列表中键入数字,然后它会为您工作。

当您使用while 语句时,无需再次调用 PerformClick() 只需将代码放入 while 循环并从外部删除即可。

但是我仍然不明白你为什么使用

 ListBox1.Items(ListBox1.SelectedIndex) = ListBox1.SelectedItem + (" ")

但是要同时编辑 20 个列表框,您应该这样做:

      Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click    
         while (ListBox1.SelectedItem.Length < SelectedProfile3.SelectedItem) And SelectedProfile3.SelectedIndex = 1
              ListBox1.Items(ListBox1.SelectedIndex) = ListBox1.SelectedItem + (" ")
              SelectedProfile3.SelectedIndex = 1
              ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
          End While
      End Sub

当您进行比较时,如果不指定控件名称就不能使用循环,它可以对每个列表框中的项目进行。

在代码中,我在 while 语句中输入了ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1然后无需再次执行单击。

如果您想一次使用 20 个列表框(不是列表项,因为您在列表框上写问题),那么您可以对列表框项使用 For 循环或 For each 循环,但应指定不同的列表名称, 否则要更改所有类似列表框形式的类似控件,请使用 {For each listbox in me.controls}。您无需一次又一次地执行此单击。

注意:在不指定唯一名称的情况下比较控件是很困难的,因为编译器不会理解您比较的内容和内容。


推荐阅读