用代码给DataGridView添加新行

来源:互联网 发布:linux 串口登陆 编辑:程序博客网 时间:2024/05/22 16:13

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

原创粉丝点击