简体   繁体   中英

How to get ListView.SubItems

I'm trying to make a program that inputs text into a document depending on the user input, and I am currently displaying it as a ListView.

I can't figure out how to get the SubItem from the item, as this is my current code.

For Each item In ListView1.Items
    Dim inputString72 As String = "@bot.command()" + vbNewLine
    My.Computer.FileSystem.WriteAllText(
      SaveFileDialog1.FileName, inputString72, True)
    Dim inputString73 As String = "async def " + item.Text + "(ctx):" + vbNewLine
    My.Computer.FileSystem.WriteAllText(
      SaveFileDialog1.FileName, inputString73, True)
    Dim inputString74 As String = "    await ctx.send('" + THE SUBITEM OF THE ITEM GOES HERE + "')" + vbNewLine
    My.Computer.FileSystem.WriteAllText(
      SaveFileDialog1.FileName, inputString74, True)
Next

I think it would be more efficient to use the .net File class. No need to call the method several times in each iteration. From the docs. "The WriteAllText method opens a file, writes to it, and then closes it. " That is a lot of openning and closing. Build a string with a StringBuilder (which is mutable) and then write once to the file.

I used interpolated strings (it is preceded by a $) which allows you to put a variable directly in a string surrounded by braces.

SubItem indexes start at 0 with the first column. The .Text property of the SubItem will return its contents.

Private Sub WriteListViewToFile(FilePath As String)
    Dim sb As New StringBuilder
    For Each item As ListViewItem In ListView1.Items
        sb.AppendLine("@bot.command()")
        sb.AppendLine($"async def {item.Text}(ctx):")
        sb.AppendLine($"    await ctx.send('{item.SubItems(1).Text}')")
    Next
    File.WriteAllText(FilePath, sb.ToString)
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If SaveFileDialog1.ShowDialog = DialogResult.OK Then
        WriteListViewToFile(SaveFileDialog1.FileName)
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM