VB.NET错误行无法通过programmaticaly添加

时间:2013-05-29 06:31:46

标签: database vb.net stored-procedures

我想从数据库中检索将在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

任何帮助人员 感谢

1 个答案:

答案 0 :(得分:1)

您实际上最初可以将数据加载到DataTable,然后使用DataGridView上的Load方法将其绑定到DataTable,然后将其设置为{ DataGridView上的{3}}属性。

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

table.Load(reader)
Me.DataGridView1.DataSource = table