在VB.NET中,从SQL查询中选择列并在网格中显示

编程语言 2026-07-09

在创建一个MP3播单生成器时,我还弄不明白下面这段代码该怎么工作。

在我的数据库中,有一个表包含了曲目的所有MP3属性,包括磁盘上的文件路径。

当我保存播放列表时,我会创建一个文本文件“{filenamesomething}.M3U”。 文件中的行格式如下:

\\DS224\music\MP3\B\Beatles, The\Beatles, The (1963) Please Please Me\01 - I Saw Her Standing There.mp3

我想对该文本文件的每一行进行读取,将这一行在SQL查询中使用,以检索所有MP3数据并将这些数据在网格中显示出来。我想通过这样做来还原表中的某些数据。

代码:

Dim sTrack As String
Dim sMP3File As String = ""

Dim i As Integer = 0
Dim sr As New StreamReader(sPath)  

DataGridView.Rows.Clear()
ConDBMusic.Open()

Do While (sString IsNot Nothing)
   If (sr IsNot Nothing) Then

      sString = sr.ReadLine     
     '\\DS224\music\MP3\A\Air Supply\Air Supply (1983)The Best\01 - Lost In Love.mp3

      sSqlSelect = "Select * From dbo.MP3Tracks Where MP3_FileName = '" & sString & "'"

      Dim Adapter As New SqlDataAdapter(sSqlSelect, ConDBMusic)
      Dim Table As New DataTable()

      Adapter.Fill(Table)

      DataGridView.Rows.Add()
      DataGridView.Rows.Item(i).Cells(0).Value = Table.Rows(0).Item("MP3_Artist")
      DataGridView.Rows.Item(i).Cells(1).Value = Table.Rows(0).Item("Mp3_Album")
      DataGridView.Rows.Item(i).Cells(2).Value = Table.Rows(0).Item("MP3_Year")

   End If

  i += 1
  sString = sr.ReadLine

 Loop

 sr.Close()

End If

ConDBMusic.Close()

这只对已读取并在数据库中查找过的第一行起作用。

当我读取下一行时,会出现一个错误

SYSTEM.IndexOutOfRangeException:在位置0 处没有该行

这和表有关,但到底是怎么回事?

解决方案

由于你初始化 Dim sr As New StreamReader(sPath)sr 将不是 Nothing。对 If (sr IsNot Nothing) 的检查是多余的。

但你应该在测试 Nothing 之前先读取 sString。你可以用一个无限循环,在字符串变成 Nothing 时退出循环。

Dim sr As New StreamReader(sPath)

Do While True
    sString = sr.ReadLine
    If sString Is Nothing Then
        Exit Do
    End If
    'TODO: do something with sString
Loop

你也可以通过使用像Dapper(简单)或EF Core(复杂但强大)这样的对象关系映射(O/R映射)来简化所有与数据库相关的工作。再结合数据绑定,这也会简化你的DataGridView代码。嗯,基本上可以说它会在很大程度上消除它。

另请参阅: ASPSnippets – Bind DataGridView using Dapper (C# & VB.NET).

但你也可以把数据加载到一个业务类中,而不是使用DataTable。我在VB中没有找到很好的示例。如果你会读C#,你会发现更多示例。

基本上你可以像下面这样做(未经过测试或编译):

Public Class MP3
    Public Property MP3_Artist As String
    Public Property Mp3_Album As String
    Public Property MP3_Year As Integer
End Class

然后,结合Dapper

Dim tracks As List(Of MP3) = New List(Of MP3)()

tracks = ConDBMusic.Query(Of MP3)("Select * From dbo.MP3Tracks").ToList()
DataGridView.DataSource = tracks
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章