DontFretBrett
DontFretBrett

Reputation: 1165

Winforms ListBox Control Not Updating After Source Changes

I have a ListBox (LB) with a DataTable (DT) DataSource in the Form Class globally populated in the Form_Load event.

Private Sub frmEditPresets_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    DT.Columns.Add("DisplayText")
    DT.Columns.Add("PresetID")
    For Each TSI As ToolStripItem In Presets.DropDownItems
        If TSI.Name.IndexOf("preset_") > -1 Then
            DT.Rows.Add(TSI.Text, TSI.Name)
        End If
    Next
    LB.DataSource = DT
    LB.DisplayMember = "DisplayText"
End Sub

When I use my Rename button. It updates the menu item and the Data Source but the Listbox doesn't refresh until I click another item in the listbox.

Rename code:

Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click
    Dim R As DataRowView = LB.SelectedItem
    Dim S As String = InputBox("Preset Name", "Rename", R("DisplayText"))
    If S.Trim.Length = 0 Then Exit Sub
    If Presets.DropDownItems.ContainsKey(R("PresetID").ToString) Then
        Presets.DropDownItems(R("PresetID").ToString).Text = S
    End If
    R("DisplayText") = S
End Sub

I'm sure this is a simple question with a simple answer but I can't seem to figure it out. I've tried Refresh(). I've tried setting the DataSource again. I read this StackOverflow question Winforms listbox not updating when bound data changes but ResetBindings() doesn't seem to be an available method in this context.

*Edit. I gave Steve credit for the answer as he mentioned BindingContext. Although, that led me to find BindingContext(DT).EndCurrentEdit() which updated my LB display and maintained the selection.

Upvotes: 3

Views: 1918

Answers (1)

Steve
Steve

Reputation: 216293

Tried with this, and it works.....

Private Sub btnRename_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRename.Click  
    Dim R As DataRowView = LB.SelectedItem  
    Dim S As String = InputBox("Preset Name", "Rename", R("DisplayText"))  
    If S.Trim.Length = 0 Then Exit Sub  
    If Presets.DropDownItems.ContainsKey(R("PresetID").ToString) Then  
        Presets.DropDownItems(R("PresetID").ToString).Text = S  
    End If  
    R("DisplayText") = S  
    BindingContext(DT).EndCurrentEdit()
End Sub  

Upvotes: 1

Related Questions