用代碼給DataGridView添加新行

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章