我想从数据库中检索将在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
任何帮助人员 感谢
答案 0 :(得分:1)
您实际上最初可以将数据加载到DataTable
,然后使用DataGridView
上的Load
方法将其绑定到DataTable
,然后将其设置为{ DataGridView
上的{3}}属性。
Dim table As New DataTable()
Dim reader = cmd.ExecuteReader()
table.Load(reader)
Me.DataGridView1.DataSource = table