0

我想从数据库中检索将在 3 天后过期的汽车授权信息,并在表单加载的数据网格中显示它们。这是我在 VB.NET 中实现的代码

Dim ConnectString As String
ConnectString = ""
Dim connection As New SqlConnection(ConnectString)
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = connection
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "AuthorizationExp"

Try
    connection.Open()

    Dim dreader As SqlDataReader
    dreader = cmd.ExecuteReader()

    While (dreader.Read())
        Dim n As Integer = DataGridView1.Rows.Add()
        DataGridView1.Rows.Item(n).Cells(0).Value = (dreader("AuthorizationNo").ToString)
        DataGridView1.Rows.Item(n).Cells(1).Value = (dreader("DriverID").ToString)
        DataGridView1.Rows.Item(n).Cells(2).Value = (dreader("PlateNo").ToString)
        DataGridView1.Rows.Item(n).Cells(3).Value = (dreader("AuthorizationStart").ToString)
        DataGridView1.Rows.Item(n).Cells(4).Value = (dreader("AuthorizationEnd").ToString)
    End While
    dreader.Close()
Catch ex As Exception
    MessageBox.Show("An error ocurred (" + ex.Message + ")")
Finally
    connection.Close()
End Try

我从存储过程中检索它们:

create procedure AuthorizationExp
as
select  CarDriver.AuthorizationNo, CarDriver.DriverID, CarDriver.PlateNo, CarDriver.AuthorizationStart, CarDriver.AuthorizationEnd
from CarDriver 
where DATEDIFF(day, GETDATE(), AuthorizationEnd) <=3

我得到的错误是

Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound

任何帮助,谢谢

4

1 回答 1

1

您实际上可以最初将数据加载到 aDataTable中,然后DataGridView使用 上的Load方法将其绑定到 ,然后将DataTable其设置DataSourceDataGridView.

Dim table As New DataTable()
Dim reader = cmd.ExecuteReader()

table.Load(reader)
Me.DataGridView1.DataSource = table
于 2013-05-29T22:54:40.913 回答