如果我声明一个字符串数组,那么我可以将此数组添加到listbox
,如下所示:
Dim a() As String = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
ListBox1.Items.AddRange(a.ToArray)
但是当我声明与整数相同的数组时,ListBox1.Items.AddRange()
给我错误
代码是
Dim a() As Integer = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
ListBox1.Items.AddRange(a.ToArray)
我得到的错误是:
Error 1 Overload resolution failed because no accessible 'AddRange' can be called with these arguments:
'Public Sub AddRange(items() As Object)':
Value of type '1-dimensional array of Integer'
cannot be converted to '1-dimensional array of Object' because 'Integer' is not a reference type.
'Public Sub AddRange(value As System.Windows.Forms.ListBox.ObjectCollection)':
Value of type '1-dimensional array of Integer' cannot be converted to 'System.Windows.Forms.ListBox.ObjectCollection'.
我知道我可以使用for循环将数组添加到列表框但是我想知道如何使用listbox
ListBox1.Items.AddRange()
使用for
For i As Integer = 0 To a.Length - 1
ListBox1.Items.Add(a(i))
Next
答案 0 :(得分:1)
如果您仔细阅读,您将看到问题所在:
类型'整数'的1维数组的值无法转换为 '对象'的一维数组,因为'整数'不是引用 类型。强>
所以你可以做的是首先框整数:
ListBox1.Items.AddRange(a.Select(Function(i) CObj(i)).ToArray())
或者更简单:
ListBox1.Items.AddRange(a.Cast(Of Object).ToArray())
最后我认为你几乎不会需要这样的东西,因为你可能希望以某种方式格式化你的数字。所以在大多数情况下,你最终会得到类似的东西:
dim formated = a.Select(Function(i) String.Format("number: {0}", i))
ListBox1.Items.AddRange(formated.ToArray())
anway,您不必关心引用类型的详细信息。
答案 1 :(得分:-1)
只需使用数据绑定并设置DataSource
属性,而不是直接添加项目。在这种情况下,任何实现IList
的东西都可以。