Imports System.Data
Imports System.Data.SqlClient
Imports System.Text
Public Class Form2
Dim dr As SqlDataReader
Dim cn As SqlConnection
Dim cm As SqlCommand
Dim sb As New StringBuilder
Dim strSql As String
Dim strCn As String = "Data Source=bkk314;Initial Catalog=DB_For_Webboard;Integrated Security=True"
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn = New SqlConnection()
With cn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = strCn '' string ที่ใช้ต่อ connection
.Open()
End With
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
sb.Remove(0, sb.Length) '' คำสั่ง Query ข้อมูล
sb.Append("Select productid,productname,price,qty,totalprice,datesales From Product")
sb.Append(" Where (datesales Between '" & DateTimePicker1.Value.ToString("MM/dd/yyy") & "' And '" & DateTimePicker2.Value.ToString("MM/dd/yyy") & "')")
strSql = sb.ToString() '' เก็บใน String
com = New SqlCommand()
With com
.CommandText = strSql
.CommandType = CommandType.Text
.Connection = cn
dr = .ExecuteReader()
End With
If dr.HasRows Then ''check dr
Dim dtSql As DataTable
dtSql = New DataTable()
dtSql.Load(dr)
With DataGridView1
.DataSource = dtSql ''**
Dim i As Integer = 0 '' วิธีแรกครับ
Dim SumPrice As Double = 0
For i = 0 To DataGridView1.Rows.Count - 1
SumPrice += CDbl(DataGridView1.Rows(i).Cells(4).Value)
Next
TextBox1.Text = SumPrice.ToString("#,##0.00")
'---------------------------------
Dim i2 As Integer = 0 ''วิธีที่สอง
Dim SumPrice2 As Double = 0
For i2 = 0 To dtSql.Rows.Count - 1 ''**
SumPrice2 += CDbl(dtSql.Rows(i2).Item("totalprice"))
Next
TextBox1.Text = SumPrice2.ToString("#,##0.00")
End With
End If
End Sub
End Class