vb.net 如何用字符串数组填充 ComboBox?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22682075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:14:00  来源:igfitidea点击:

How to populate a ComboBox with a string array?

arraysvb.netcombobox

提问by Mox

Private Sub frmQuery3_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    frmQuery2.Hide()
    Dim columns As String = frmQuery2.GetColumns
    cmbColumnSort.MaxDropDownItems = columns.Length
    For stepper = 0 To (columns.Length - 1)
        cmbColumnSort.Items.Add(columns(stepper))
    Next
End Sub

cmbColumnSort is initially an empty ComboBox. What I would like to do is fill the ComboBox with the string array columns, which shouldn't empty(it certainly isn't in frmQuery2).

cmbColumnSort 最初是一个空的 ComboBox。我想要做的是用字符串数组列填充 ComboBox,它不应该为空(它肯定不在 frmQuery2 中)。

The thing is, it doesn't work. I've tried a Step Into to see whether the property GetColumns actually returns a filled array(as the array in frmQuery2 is filled), but the Step Into just skips from the third line of the above code and loads the form, awaiting further input, and leaving the ComboBox empty. Help?

问题是,它不起作用。我尝试了 Step Into 以查看属性 GetColumns 是否实际返回了一个填充数组(因为 frmQuery2 中的数组已填充),但 Step Into 只是从上述代码的第三行跳过并加载表单,等待进一步输入,并将 ComboBox 留空。帮助?

回答by Fux

In case you don't want to create array

如果您不想创建数组

ComboBox1.DataSource = {"Text1", "Text2", "Text3"}

回答by profimedica

ComboBox1.Items.AddRange(columns)

回答by ?s??? ????

You need a string array to get columns, so use Dim columns() As String

您需要一个字符串数组来获取列,因此请使用 Dim columns() As String

The below code is working fine

下面的代码工作正常

    Dim columns() As String = {"1", "2", "3"}
    ComboBox1.MaxDropDownItems = columns.Length
    For stepper = 0 To (columns.Length - 1)
        ComboBox1.Items.Add(columns(stepper))
    Next

I suggest you make your code clearer and easier to write using For Each

我建议你让你的代码更清晰,更容易编写使用 For Each

    Dim columns() As String = {"1", "2", "3"}
    ComboBox1.MaxDropDownItems = columns.Length
    For Each column As String In columns
        ComboBox1.Items.Add(column)
    Next