如何用代码修改combobox下拉列表?
2个回答
展开全部
用代码修改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)运行效果
启动时
单击“水果类”命令按钮后
单击“主食类”命令按钮后
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询