[转]VB.NET中怎样为listview绑定数据
Cames from CSDN
'从数据库中读取数据插入到listview中.
'注意:要显示网格,必须将listview中的view设置为details,然后再将gridline设置为true .
'设完之后,用鼠标只能点击listview中的第一个角落,点击其他的地方不起作用,需要设置
'listview中的FullRowSelect属性才可以.这样就可以选中一行了.
Dim MyCmd As SqlClient.SqlCommand
Dim MyCnn As New SqlClient.SqlConnection
Dim myDrd As SqlClient.SqlDataReader
MyCnn.ConnectionString = "Server=localhost;user id=sa;password=;database=NHSP"
Dim t As String = "select * from BA_USER"
'如果要用该控件查询,则只需要改变"select * from BA_USER where 条件"就可以了
MyCmd = New SqlClient.SqlCommand(t, MyCnn)
MyCnn.Open()
myDrd = MyCmd.ExecuteReader
Dim iHead As Integer
Dim head(5) As String
'head(0) = "a"
'head(1) = "b"
Me.lvw.Columns.Clear()
For iHead = 0 To myDrd.FieldCount - 1
Me.lvw.Columns.Add(myDrd.GetName(iHead), 100, HorizontalAlignment.Center)
Next
'加入listview列数据()
Me.lvw.Items.Clear()
Dim iRow As Long = 0
Dim iRowHead As Int16
Do While myDrd.Read
Me.lvw.Items.Add(myDrd(0))
For iRowHead = 1 To myDrd.FieldCount - 1
If (myDrd(iRowHead) Is System.DBNull.Value = False) Then
Me.lvw.Items(iRow).SubItems.Add(CStr(myDrd(iRowHead)))
Else
Me.lvw.Items(iRow).SubItems.Add("")
End If
Next
iRow = iRow + 1
Loop
MyCnn.Close()
MyCnn.Dispose()