How do I make a ListBox refresh its item text?

前端 未结 10 1988
后悔当初
后悔当初 2020-12-03 04:42

I\'m making an example for someone who hasn\'t yet realized that controls like ListBox don\'t have to contain strings; he had been storing formatted strings and

10条回答
  •  鱼传尺愫
    2020-12-03 04:59

    Use the datasource property and a BindingSource object in between the datasource and the datasource property of the listbox. Then refresh that.

    update added example.

    Like so:

    Public Class Form1
    
        Private datasource As New List(Of NumberInfo)
        Private bindingSource As New BindingSource
    
        Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
            MyBase.OnLoad(e)
    
            For i As Integer = 1 To 3
                Dim tempInfo As New NumberInfo()
                tempInfo.Count = i
                tempInfo.Number = i * 100
                datasource.Add(tempInfo)
            Next
            bindingSource.DataSource = datasource
            ListBox1.DataSource = bindingSource
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            For Each objItem As Object In datasource
                Dim info As NumberInfo = DirectCast(objItem, NumberInfo)
                info.Count += 1
            Next
            bindingSource.ResetBindings(False)
        End Sub
    End Class
    
    Public Class NumberInfo
    
        Public Count As Integer
        Public Number As Integer
    
        Public Overrides Function ToString() As String
            Return String.Format("{0}, {1}", Count, Number)
        End Function
    End Class
    

提交回复
热议问题