Imports System.Data.SqlClient
Public Class Form1
Dim connection As New SqlConnection( _
"Data Source=SZC002;Initial Catalog=Northwind;" & _
"Persist Security Info=True;User ID=sa")
Dim command As New SqlCommand
Dim reader As SqlDataReader
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Using connection
connection.Open()
command.CommandText = "Select top 10 CustomerId,CompanyName From Customers"
command.Connection = connection
reader = command.ExecuteReader()
While reader.Read
Dim row As New DataGridViewRow()
Dim cell As DataGridViewTextBoxCell
cell = New DataGridViewTextBoxCell
cell.Value = reader("CustomerId").ToString
row.Cells.Add(cell)
cell = New DataGridViewTextBoxCell
cell.Value = reader("CompanyName").ToString
row.Cells.Add(cell)
With DataGridView1
方式1:.Rows.Add(New String() {reader("CustomerId").ToString, reader("CompanyName").ToString})
方式2:.Rows.Add(row)
End With
End While
connection.Close()
End Using
End Sub
End Class