如何将数据库查询结果填充到列表视图。我遇到了问题" Form1.ListView1.Items(i).SubItems(1).Text = myRow.Item(0)"。
Dim cn As New SqlConnection()
Dim WFTeam As New DataSet()
Dim da As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim myRow As DataRow
Dim dt As New DataTable
Dim strSqlStm As String = ""
Dim strConnectionString As String = ""
strSqlStm = "SELECT [SRF#], [FirstName], [LastName] FROM [Agent] WHERE [TeamLeaderNo] = 103"
cn.ConnectionString = strDataSource & "Initial Catalog=EmployeeDatabase;" & strUID & strPassword
cn.Open()
da = New SqlDataAdapter(strSqlStm, cn)
cmdBuilder = New SqlCommandBuilder(da)
da.Fill(WFTeam, "Team")
WFTeam.Tables.Add(dt)
da.Fill(dt)
Form1.ListView1.Items.Clear()
Dim i As Integer = 1
For Each myRow In dt.Rows
If Not IsDBNull(myRow.Item(0)) Then
Form1.ListView1.Items(i).SubItems(1).Text = myRow.Item(0)
End If
If Not IsDBNull(myRow.Item(1)) Then
Form1.ListView1.Items(i).SubItems(2).Text = myRow.Item(1)
End If
If Not IsDBNull(myRow.Item(2)) Then
Form1.ListView1.Items(i).SubItems(3).Text = myRow.Item(2)
End If
i = i + 1
Next
cn.Close()
以下代码有效,但我需要像Excel一样访问特定项目
For Each myRow In dt.Rows
If Not IsDBNull(myRow.Item(0)) Then
Form1.ListView1.Items.Add(myRow.Item(0))
'Form1.ListView1.Items(i).SubItems(1).Text = myRow.Item(0)
End If
If Not IsDBNull(myRow.Item(1)) Then
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(myRow.Item(1))
'Form1.ListView1.Items(i).SubItems(2).Text = myRow.Item(1)
End If
If Not IsDBNull(myRow.Item(2)) Then
Form1.ListView1.Items(Form1.ListView1.Items.Count - 1).SubItems.Add(myRow.Item(2))
'Form1.ListView1.Items(i).SubItems(3).Text = myRow.Item(2)
End If
i = i + 1
Next
答案 0 :(得分:0)
您清除了LV,因此没有要填充的Items或SubItems。您需要创建新的ListViewItem并使用DB数据填充它们。但是,如果第一个提交IsDbNull,则您的编辑会跳过添加项目,这意味着您无法为该记录添加任何内容。以下也将“锚定”数据,因此当任何子项数据IsDbNull时,下一个子项不会超过一个:
Form1.ListView1.Items.Clear()
Dim lvi As ListViewItem
For Each myRow In dt.Rows
' create NEW listview item for this row
lvi = New ListViewItem
If IsDBNull(myRow.Item(0)) Then
lvi.Text = " " ' blank Item
Else
lvi.Text = myRow.Item(0)
End If
' repeat for the sub items, adding blanks when DbNull
If IsDBNull(myRow.Item(1)) Then
lvi.SubItems.Add(" ")
Else
lvi.SubItems.Add(myRow.Item(1))
End If
' etc
Form1.ListView1.Items.Add(lvi)
Next
DataGridView
比ListView
更适合这种情况,特别是访问类似于Excel的项目。我认为这意味着你希望myRow.Item(2)
永远是第二个子项目。因此,上面的代码将空Items或SubItems添加为“占位符”。