从ms-access获取值并添加所有值Vb.Net

时间:2016-08-07 23:19:13

标签: database vb.net ms-access-2007

我的数据库ms-access包含表'客户端'这个表包含:(ClientName,ClientPhone,ClientAddress,ClientCredit,ClientDes)__ ok!我想在我的软件vb.net中添加ClientCredit的所有值。我使用这个代码和它的工作,但我给它一个错误的价值!!

Dim credit As Double = 0    
Try
    Dim dt As DataTable = New DBConnect().selectdata( _
          "SELECT ClientName, ClientPhone, ClientAddress, ClientCredit, ClientDes FROM Client;")
    For i As Integer = 0 To dt.Rows.Count - 1
        credit = dt.Rows(0)(3).ToString + credit
    Next
Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try
FlatTextBox1.Text = credit    

此代码给出结果:400但实际结果是415.2

2 个答案:

答案 0 :(得分:0)

您不在循环中使用索引i。将代码修改为Rows(i)而不是Rows(0)

   For i As Integer = 0 To dt.Rows.Count - 1
        //credit = dt.Rows(0)(3).ToString + credit                   
        // credit is double, why ToString 
        credit = Convert.ToDuble(dt.Rows(i)(3)) + credit          
    Next

其他解决方案:

您可以避免循环(删除..next)并使用DataTable的Compute方法:

     credit = dt.Compute("Sum(ClientCredit)", "");

答案 1 :(得分:0)

你的求和线:

credit = dt.Rows(0)(3).ToString + credit

应该阅读

credit += TryCast(dt.Rows(i)(3), Double)