我正在开发一个VB类的项目,我将一个访问数据库连接到VB项目,并将数据分开显示。我很难找到能够完成这项任务的特定行代码。
我所要做的就是将一列年龄分成3组,然后将这些信息分成3个文本行。
我知道循环非常好但我找不到确切的代码措辞去数据库并解析出来......
到目前为止,这是所有代码......
Public Class frmSportsLeague
Private Sub TeamBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TeamBindingNavigatorSaveItem.Click
Me.Validate()
Me.TeamBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.LittleLeagueDataSet)
End Sub
Private Sub frmSportsLeague_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'LittleLeagueDataSet.Team' table. You can move, or remove it, as needed.
Try
TeamTableAdapter.Fill(Me.LittleLeagueDataSet.Team)
Catch
MsgBox("The database is not there!!!")
End Try
End Sub
Private Sub btnAge_Click(sender As Object, e As EventArgs) Handles btnAge.Click
'strSQL is an SQL statement that selects and imports all fields from the gardener database
Dim strsql As String = "SELECT * FROM Team"
Dim strPath As String = "Provider=Microsoft.ACE.OLEDB.12.0 ;" & "Data Source = C:\Windows\Temp\LittleLeague.accdb"
Dim odaLittleLeague As New OleDb.OleDbDataAdapter(strsql, strPath)
Dim datPlayers As New DataTable
Dim intCount As Integer
Dim intTwelve As Integer = 0
Dim intThirteen As Integer = 0
Dim intFourteen As Integer = 0
Dim decAllAges As Decimal = 0D
Dim decAverage As Decimal = 0D
Dim intPlayers As Integer
btnAge.Visible = False
'The datCost DataTable gets the table data imported
odaLittleLeague.Fill(datPlayers)
'The connection to the database is closed
odaLittleLeague.Dispose()
For intCount = 0 To datPlayers.Rows.Count - 1
decAllAges += Convert.ToDecimal(datPlayers.Rows(intCount)("Age"))
Next
intPlayers = datPlayers.Rows.Count
decAverage = decAllAges / intPlayers
lblTwelve.Visible = True
lblTwelve.Text = "The number of 12 year old players is: " & intTwelve.ToString()
lblThirteen.Visible = True
lblThirteen.Text = "The number of 13 year old players is: " & intThirteen.ToString()
lblFourteen.Visible = True
lblFourteen.Text = "The number of 14 year old players is: " & intFourteen.ToString()
lblAverage.Visible = True
lblAverage.Text = "The average age of all the players is: " & decAverage.ToString("F2")
End Sub
结束班
答案 0 :(得分:0)
假设年龄在数据库中存储为文本(没有数据库规范,但我可以看到您的代码中有一个转换为十进制),在代码中添加“select case”应该执行特技。修改后的循环:
For intCount = 0 To datPlayers.Rows.Count - 1
decAllAges += Convert.ToDecimal(datPlayers.Rows(intCount)("Age"))
Select Case (datPlayers.Rows(intCount)("Age"))
Case "12"
intTwelve += 1
Case "13"
intThirteen += 1
Case "14"
intFourteen += 1
Case Else
MsgBox("Error: Age not in range 12-14!")
End Select
Next