3

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.

Community
  • 1
  • 1
DontFretBrett
  • 1,135
  • 3
  • 17
  • 32
  • Many controls can't know when something inside an object has change. If I have a BindingList of `Foo`, it may know if I add/remove a `Foo`, but it doesn't know if `Foo.Property` has changed. To communicate those changes, `Foo` would need to implement INotifyPropertyChanged. Something similar might be at work here. – Jeff B Jun 29 '12 at 17:49

1 Answers1

1

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  
Steve
  • 213,761
  • 22
  • 232
  • 286