2014-01-10 48 views
0

我正在創建一個顯示數據表的Windows窗體。我還希望能夠從顯示的表格中選擇一行,並在調用它的表單上顯示信息。我已連接到服務器,但似乎無法填充數據表。在WinForms中顯示數據表

Dim Students As String = "select * from dbo.[students]" 
Dim Studentscmd As New SqlCommand(Students, cnn) 
Dim Studentstable As New DataTable 
Dim Studentadapter As New SqlDataAdapter 

Dim NStudents As DataSet = New DataSet() 
Studentadapter.Fill(NStudents) 

Datagridview.DataGridView1.DataSource = NStudents 
Datagridview.DataGridView1.Show() 
+0

你的DataAdapter和你的命令或連接之間沒有聯繫,我可以看到。基本上你定義一個新的適配器並傳遞一個空的DataSet。看看MSDN中的例子,你應該怎麼做。 – DarrenMB

+0

FILL命令前缺少'StudentAdapter.SelectCommand = StudentsCmd' – DarrenMB

回答

1

試試這個:
(如@DarrenMB提到你SqlAdapterSqlCommand之間缺少聯繫)

Dim Students As String = "select * from dbo.[students]" 
Dim Studentstable As New DataTable() 
Using Studentscmd As New SqlCommand(Students, cnn) 
    Using Studentadapter As New SqlDataAdapter(Studentscmd) 'This link Adapter with command 
     Studentadapter.Fill(Studentstable) 'Can fill straight to DataTable 
    End Using 
End Using 
Datagridview.DataGridView1.DataSource = Studentstable 
Datagridview.DataGridView1.Show() 

「更好的做法」 使用Using statement當處理像數據庫非託管資源
End UsingUsing創建的所有對象和資源將被正確處置/釋放