2013-05-29 62 views
0

我想檢索將在數據庫3天后過期的汽車授權信息,並將它們顯示在表單加載中的數據網格中。這是我在VB.NET實現的代碼VB.NET錯誤行不能添加programmaticaly

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

你不能用數據綁定的DataGrid中添加行..插入記錄到數據源.. – matzone

+0

如果你不將數據直接加載到DataGridView,你可以嘗試不具約束力這一切。或者讓你自己的表綁定到datagridview並用數據加載表。您可以將該行添加到表格中。 – tinstaafl

回答

1

您實際上可以將您的數據初始加載到DataTable,然後使用DataTable上的Load方法將其綁定到DataGridView,然後將其設置爲DataGridView上的DataSource屬性。

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

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