【问题标题】:Removing a Duplicate Item from ListBox converted into a string从转换为字符串的 ListBox 中删除重复项
【发布时间】:2021-10-17 23:34:20
【问题描述】:

我有一个问题,当我从ListBox 中取出项目并将它们转换为单行字符串时,它会复制最后一个项目。我的目标是让它只获取ListBox 中的项目,并将其转换为单行文本,用逗号分隔(,)。

我花了一些时间,但我在this thread 上找到了一些代码,它在大多数情况下都有效,但最后一项在转换为字符串时总是重复的。我正在使用的代码是:

        Dim item As Object
        Dim List As String
      
        ' Other unrelated code

        ' Credit: T0AD - https://www.tek-tips.com/viewthread.cfm?qid=678275
        For Each item In Form1.ListBox1_lstbox.Items
            List &= item & ","
        Next

        'To remove the last comma.
        List &= item.SubString(0, item.Length - 0) 
        ' This is weird, but setting item.Length - 1 actually removes two characters.

        ' Add text to textbox
        TextBox1.Text = List

我感觉它必须处理删除逗号的代码,因为它是一个 &= 再次调用 item Dim。但我似乎无法弄清楚该怎么做。

输出示例如下:Item1,Item2,Item3,Item3

当我想要这个时:Item1,Item2,Item3

【问题讨论】:

  • String.Join(",", ListBox1.Items.Cast(Of Object)) 怎么样? (根据需要调整 ListBox 名称。)
  • 以及为什么它没有在List &= item.SubString(0, item.Length - 0)行中做你想做的事情的答案:你可能打算写List = List.SubString(0, List.Length - 1)。 (另外,List 是一个不好的变量名称,因为当您习惯了 List(Of T) 时,它会变得更难阅读。)
  • 谢谢。我不知道为什么我要采用更复杂的方法来做到这一点。至于 List 变量,我实际上为示例更改了它。我尝试使用不同的String.Join 方法,但是当我尝试执行它时它导致它崩溃。但这种方法有效。至于List &= item.SubString(0, item.Length - 0),我实际上是想写它,因为用-1 写它会导致它删除两个字符,逗号,加上列表中的最后一个字符。

标签: vb.net visual-studio-2022


【解决方案1】:

你的问题在于这条线。

List &= item.SubString(0, item.Length - 0)

您正在使用&=List 添加另一个字符串。您要添加的字符串是来自For Each 循环的item 的最终值。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If ListBox1.Items.Count = 0 Then
        MessageBox.Show("There are no items in the list box.")
        Exit Sub
    End If
    Dim List As String = ""
    For Each item In ListBox1.Items
        List &= item.ToString & ","
    Next
    List = List.Substring(0, List.Length - 1)
    TextBox1.Text = List
End Sub

@Andrew Morton 在 cmets 中提供的附加解决方案,不需要 ListBox 包含项目。

TextBox1.Text = String.Join(",", ListBox1.Items.Cast(Of Object))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    • 2011-02-06
    相关资源
    最近更新 更多