Binding a ListBox's SelectedItem in the presence of BindingNavigator

Posted by Reinderien on Stack Overflow See other posts from Stack Overflow or by Reinderien
Published on 2010-06-16T21:57:17Z Indexed on 2010/06/16 22:22 UTC
Read the original article Hit count: 285

Filed under:
|
|
|

Hello. I'm trying to bind a ListBox's SelectedItem data to a property. The following code is an example:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace BindingFailure
{
 static class Program
 {
  class OuterObject
  {
   public string selected { get; set; }
   public List<string> strings { get; set; }
  }

  public static void Main()
  {
   List<OuterObject> objs = new List<OuterObject>()
   {
    new OuterObject(), new OuterObject()
   };
   objs[0].strings = new List<string> { "one", "two", "three" };
   objs[1].strings = new List<string> { "four", "five", "six" };

   Form form = new Form();

   BindingSource obs = new BindingSource(objs, null),
    ibs = new BindingSource(obs, "strings");
   BindingNavigator nav = new BindingNavigator(obs);
   ListBox lbox = new ListBox();
   lbox.DataSource = ibs;
   lbox.DataBindings.Add(new Binding("SelectedItem", obs, "selected"));

   form.Controls.Add(nav);
   form.Controls.Add(lbox);
   lbox.Location = new System.Drawing.Point(30, 30);

   Application.Run(form);
  }
 }
}

If you just select an item, move forward, select an item and then exit, it works as expected. But if you switch back and forth between the two outer objects with the navigator, the selected item seems to be overwritten with an incorrect value.

Ideas on how to fix this? Thanks in advance.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET