将数据从二维数组显示到组合框和文本框中

时间:2016-12-21 00:27:03

标签: arrays vb.net combobox

我在vb.net中有一个二维数组项目和价格:

Dim items(,) As String = {{"Chicken Sand", "9000"}, {"Roast Beef Sand", "13500"}, 
                 {"Salmon Sand", "13500"}, {"Tuna Sand", "11000"},
                 {"Halloumi Sandwich", "7000"}, {"Ham & Cheese Sand", "8000"}, 
                 {"Water", "1500"}, {"Soft Drink", "2500"}, 
                 {"Fresh Lemonade", "3000"}, {"Fresh Orange", "3500"}}

我想用这个数组中的项填充组合框 当选择组合框中的每个项目时,我希望价格将显示在特定于价格的文本框中。 我到达了:

For row = 0 To items.GetUpperBound(0)
    cbitem.Items.Add(items(row, 0))
Next`

1 个答案:

答案 0 :(得分:2)

this is a homework and we were asked to fill the combobox with items by a two dimentional array

与使用数据源相比,这不是一个好方法:

您实际上无法将数组放入ComboBox,因为Items是一个集合,而不是多D数组。但您可以使用它来查找所选内容。确保您的数组具有表单级别范围:

Option Strict On
Public Class MenuFrm

    Private items(,) As String = {{"Chicken Sand", "9000"}, {"Roast Beef Sand", "13500"},
                    {"Salmon Sand", "13500"}, {"Tuna Sand", "11000"},
                    {"Halloumi Sandwich", "7000"}, {"Ham & Cheese Sand", "8000"},
                    {"Water", "1500"}, {"Soft Drink", "2500"},
                    {"Fresh Lemonade", "3000"}, {"Fresh Orange", "3500"}}

稍后,也许在表单加载中,使用名称填充cbo:

For row = 0 To items.GetUpperBound(0)
    cbox1.Items.Add(items(row, 0))
Next

现在,当他们选择一些东西时,查找字符串价格:

Private Sub cbox1_SelectedIndexChanged1(sender As Object, 
        e As EventArgs) Handles cbox1.SelectedIndexChanged
    If cbox1.SelectedIndex < 0 Then Return
    Dim price = Convert.ToDecimal(items(cbox1.SelectedIndex, 1))
End Sub

正确的DataSource会将价格存储为数字,并将价格与菜单项保持一致,并在SelectedValueChanged中将其全部显示。