vb 如何用代码修改combobox下拉列表
发布网友
发布时间:2022-04-27 07:48
我来回答
共4个回答
热心网友
时间:2022-04-11 23:42
用代码修改ComboBox中列表项,动态修改列表框中显示项目的实现方法如下:
(1)在Form1上布置控件,如下图所示
将Combo1的Style属性修改为:2 - DropDownList
(2)Form1代码
Option Explicit
' 自定义类型:列表框中显示的项目
Private Type ItemType
Name As String '名称
Category As Integer '类别编码
End Type
'------------------------------------------------------
' BuildComboItems
' BuildComboItems子程序动态修改列表框要显示的内容
' Items() As ItemType 是要显示内容数组
'------------------------------------------------------
Private Sub BuildComboItems(Items() As ItemType)
Dim i As Integer
With Combo1
' 清空Combo1原来的内容
.Clear
' 将内容数组Items各项添加到Combo1
For i = LBound(Items) To UBound(Items)
'在Combo1中显示“名称”
.AddItem Items(i).Name
'项目数据为改项目的类别编码
.ItemData(.NewIndex) = Items(i).Category
Next
If .ListCount > 0 Then
'默认选择第一项
.ListIndex = 0
End If
End With
End Sub
Private Sub Combo1_Click()
'单击Combo1后,Label1显示用户的选择结果
Dim description As String
With Combo1
description = "品名:" + .Text + " 类别:" + CStr(.ItemData(.ListIndex))
End With
Label1.Caption = description
End Sub
Private Sub Command1_Click()
' 创建“水果类”项目数组
Dim Fruits(1 To 4) As ItemType
Fruits(1).Name = "苹果"
Fruits(1).Category = 1
Fruits(2).Name = "橘子"
Fruits(2).Category = 2
Fruits(3).Name = "香蕉"
Fruits(3).Category = 3
Fruits(4).Name = "草莓"
Fruits(4).Category = 4
' 在Combo1中动态添加水果类项目
BuildComboItems Fruits
End Sub
Private Sub Command2_Click()
' 创建“主食类”项目数组
Dim Food(1 To 4) As ItemType
Food(1).Name = "米饭"
Food(1).Category = 10
Food(2).Name = "面条"
Food(2).Category = 11
Food(3).Name = "饺子"
Food(3).Category = 12
Food(4).Name = "包子"
Food(4).Category = 13
' 在Combo1中动态添加“主食类”项目
BuildComboItems Food
End Sub
Private Sub Form_Load()
Command1.Caption = "水果类"
Command2.Caption = "主食类"
Label1.Caption = ""
Combo1.Clear
End Sub
(3)运行效果
启动时
单击“水果类”命令按钮后
单击“主食类”命令按钮后
热心网友
时间:2022-04-12 01:00
定义一个数组变量 ,然后给combobox
Dim a() As String = {"天空", "海洋", "大地", "地球"}
ComboBox1.DataSource = a
热心网友
时间:2022-04-12 02:34
没有同时添加很多项的写法
Combo1.Clear
Combo1.AddItem "天空"
Combo1.AddItem "海洋"
Combo1.AddItem "大地"
Combo1.ListIndex=0 '(这句可加可不加、作用自己试)
热心网友
时间:2022-04-12 04:26
Form1.Combo1.Text= ""
Form1.Combo1.AddItem "天空"
Form1.Combo1.AddItem "海洋"
Form1.Combo1.AddItem "大地"