我试图让我的标签根据我的cbo选择显示信息。 (即cbo = Class Name,然后标签将显示类标题和单位。)
Dim l As Integer
'Connect to Database and get the registration information
Using cnnOLEDB = New OleDbConnection(strConnectionString)
' Query the classschedule table for start of semester datas
Using cmdOleDB = New OleDbCommand("SELECT [CourseTitle], [ShortTitle],[Units] FROM [Course]", cnnOLEDB)
cnnOLEDB.Open()
Using rdrOLEDB = cmdOleDB.ExecuteReader
While rdrOLEDB.Read
CboCourse.Items.Add(rdrOLEDB.Item(0).ToString)
CourseArray(l, 0) = rdrOLEDB.Item(0).ToString
CourseArray(l, 1) = rdrOLEDB.Item(1).ToString
CourseArray(l, 2) = rdrOLEDB.Item(2).ToString
l = l + 1
lblCourseTitle.Text = (rdrOLEDB.Item(1).ToString)
lblUnits.Text = (rdrOLEDB.Item(2).ToString)
' CboFormat.Items.Add()
' CboDayTime.Items.Add()
' CboLocation.Items.Add()
' CboName.Items.Add()
End While
End Using
End Using
End Using
我知道这可能很容易,但我无法弄明白。
我的信息在一个从MS访问数据库中读取的数组
答案 0 :(得分:1)
我真的建议你避免使用ArrayList类。这是.NET Framework中可用的第一个集合类之一,但现在我们有很多选择来在集合中存储对象实例。对于你的情况,List(Of T)可能绰绰有余。
所以让我们开始定义我们的T(课程类)
Public Class Course
Public Title As String
Public ShortTitle As String
Public Units As Integer
End Class
使用这个类你可以声明一个List(Of Course)而不是无类型的ArrayList
Dim courseList = New List(Of Course)
并且从数据库读取数据的代码变为
.....
Using rdrOLEDB = cmdOleDB.ExecuteReader
While rdrOLEDB.Read
Dim cc = New Course()
cc.Title = rdrOLEDB.Item(0).ToString
cc.ShortTitle = rdrOLEDB.Item(1).ToString
cc.Units = Convert.ToInt32(rdrOLEDB.Item(2))
courseList.Add(cc)
End While
End Using
在循环结束时,关闭所有using语句后,将组合的DataSource设置为courseList
cboCourse.DataSource = courseList
cboCourse.DisplayMember = "Title"
cboCourse.ValueMember = "Title"
此时,在SelectedIndexChanged事件处理程序中,您可以通过这种方式检索所选项目
Sub cboCourse_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim cbo = CType(sender, ComboBox )
Dim cc = CType(cbo.SelectedItem, Course)
If cc IsNot Nothing
lblCourseTitle.Text = cc.ShortTitle
lblUnits.Text = cc.Units.ToString()
End If
End Sub
答案 1 :(得分:1)
您可以使用数据绑定来轻松轻松地处理数据。
在下面的代码中,我们设置标签以使用数据绑定,并使用组合框作为索引。因此,当您从组合框中选择课程时,标签将自动显示相关数据:
'Setup connection and command
Dim Connection As String = "Your connection string here"
Dim Command As String = "SELECT [CourseTitle], [ShortTitle],[Units] FROM [Course]"
Dim DataAdapter As New OleDbDataAdapter(Command, Connection)
Dim Table As New DataTable()
'Load data
DataAdapter.Fill(Table)
'Set data bindings
Me.ShortTitleLabel.DataBindings.Add(New Binding("Text", Table, "ShortTitle"))
Me.UnitsLabel.DataBindings.Add(New Binding("Text", Table, "Units"))
'Use a data bound combo box as index
Me.CourseComboBox.DataSource = Table
Me.CourseComboBox.DisplayMember = "CourseTitle"
不要忘记导入Imports System.Data.OleDb