被修改
嗨我有这个程序,我需要在从数据库中读取时显示值的总和。我试过这样的事情:
Dim selec As String
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\rose&mike\Desktop\DbSysDel3\salondbaccess.accdb")
Dim dt2 As New DataTable
selec = ""
con.Open()
For Each incheck In chcklstbx1.CheckedIndices
Dim valName As String
valName = chcklstbx1.Items.Item(incheck).ToString
Dim sqlstr2 As String = "SELECT Service_Fee FROM Service_Types WHERE [Service_Name] = '" & valName & "'"
Dim cmd As New OleDbCommand(sqlstr2, con)
Dim sum As Double = 0
Dim rdr As OleDbDataReader = cmd.ExecuteReader
If rdr.HasRows Then
While rdr.Read
selec += "P" + rdr("Service_Fee").ToString & ControlChars.NewLine
sum = sum + rdr("Service_Fee")
End While
End If
lblFees.Text = selec
lblTotal.Text = sum.ToString
rdr.Close()
Next
con.Close()
但它所做的只是在检查时显示我想要逐个添加的值。
答案 0 :(得分:0)
这是一个如何处理整个事情的例子:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using connection As New OleDbConnection("connection string here"),
adapter As New OleDbDataAdapter("SELECT Name, Amount FROM MyTable", connection)
Dim table As New DataTable
adapter.Fill(table)
'Bind the DataTable to the CheckedListBox.
'Normally the DataSource should be set last but, in my experience, that can cause problems with a CheckedListBox.
With CheckedListBox1
.DataSource = table
.DisplayMember = "Name"
.ValueMember = "Amount"
End With
End Using
End Sub
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
'Get all the currently checked items.
Dim checkedItems = CheckedListBox1.CheckedItems.Cast(Of DataRowView)().ToList()
'Get the item that is being checked or unchecked.
Dim currentItem = DirectCast(CheckedListBox1.Items(e.Index), DataRowView)
If e.NewValue = CheckState.Checked Then
'The current item is being checked so add it to the list.
checkedItems.Add(currentItem)
Else
'The current item is being unchecked so remove it from the list.
checkedItems.Remove(currentItem)
End If
'Sum the Amounts from each checked item.
Dim sum = checkedItems.Sum(Function(drv) CDec(drv("Amount")))
'Use sum here.
'...
End Sub
您可以预先获得所有数据,包括要显示的所有文本以及所有相关的数值。该数据可以作为CheckedListBox
绑定到DataTable
,并将其全部打包在一起。
每次用户选中或取消选中列表中的项目时,都会根据您已有的数据执行计算。无需返回数据库。
关于ItemCheck
事件需要注意的重要事项是,在选中或取消选中项目之前,它会被引发。这就是代码需要对当前项目进行广告或将其从已检查项目列表中删除的原因。
绑定DataTable
时,每个绑定的项目都是DataRowView
,即表格DefaultView
中的项目。您将获得所有已检查的DataRowView
项,获取它们的数值并将它们相加。请注意,我已经使用LINQ查询来简洁地计算总和,但如果您愿意,可以使用循环,例如。
Dim sum As Decimal = 0D
For Each drv In checkedItems
sum += CDec(drv("Amount"))
Next