1.VB2008.NET中DataGrid控件的使用
http://www.002pc.com/master/College/Programming/aspnet/13233.html
在VB6 在,ADO是大家在数据库编程中用得较多的。而在新的vb.net中,虽然也可以用它来查询数据库,但在与新的datagrid的绑定中,不能像以前那样使用:“datagrid1.datasoure=rs”,而是需要一定的转化。因为新的datagrid.datasoure所对应的是 datatable或dataset,而并不是原来的Recordset。所以,在使用中,要把Recordset转换成datatable或 dataset。
结合上一篇的代码:
Function RecordsetToDataTable(ByVal adoRS As ADODB.Recordset, ByVal strTable As String)
adoRS.MoveFirst()
Dim dt As DataTable
dt = New DataTable(strTable)
Dim i As Integer
Dim strcolname As String
Dim t As Type
Dim dr As DataRow
For i = 0 To adoRS.Fields.Count - 1
strcolname = adoRS.Fields(i).Name
t = adoRS.Fields(i).Value.GetType()
dt.Columns.Add(strcolname, t)
Next
While (Not adoRS.EOF)
dr = dt.NewRow()
For i = 0 To adoRS.Fields.Count - 1
dr(i) = adoRS.Fields(i).Value
Next
dt.Rows.Add(dr)
adoRS.MoveNext()
End While
Return dt
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Con.ConnectionString = "Dbq=" & Application.StartupPath & "/Test.mdb;Driver={Microsoft Access Driver (*.mdb)}"
Con.Open()
Rec.CursorType = 1
Rec.LockType = 3
Rec.ActiveConnection = Con
Rec.Open("Student") '("Select * From Student", Con)
AxDataGrid1.DataSource = Rec
AxDataGrid1.Refresh()
Dim dts As DataTable
'dts = RecordsetToDataTable(rsuser, "login") '其中rsuser为ado.Recordset,"login"为表名
dts = RecordsetToDataTable(Rec, "Student")
DataGrid1.DataSource = dts.DefaultView
End Sub
2.运行程序后