1
votes

I have a ListBox that is bound to a BindingList collection. This works great.

My only grief occurs when the first item enters the collection. The default behavior of the ListBox is to select that item - yet, this does not raise the SelectedIndexChanged event. I assume this is because the SelectedIndex is initially set to null; on becoming anything but null, the index isn't actually changed; rather assigned. How can I stop the default behavior of selecting (highlighting) the first initial item added to the ListBox?

If my assumption is wrong, please shed some light?

Update

Here is the core parts of my code thus far.

    public UavControlForm()
    {
        InitializeComponent();
        _controlFacade = new UavController.Facade.ControlFacade();
        UpdateFlightUavListBox();
    }

    private void UpdateFlightUavListBox()
    {
        lsbFlightUavs.DataSource = _controlFacade.GetFlightUavTally();
        lsbFlightUavs.DisplayMember = "Name";
    }

    private static BindingList<FlightUav> _flightUavTally = new BindingList<FlightUav>();
    public BindingList<FlightUav> FlightUavTally
    {
        get { return _flightUavTally; }
    }

    public void AddFlightUav(double[] latLonAndAlt)
    {
        FlightUav flightUav = new FlightUav();
        flightUav.Latitude = latLonAndAlt[0];
        flightUav.Longitude = latLonAndAlt[1];
        flightUav.Altitude = latLonAndAlt[2];
        _flightUavTally.Add(flightUav);

        UtilStk.InjectAircraftIntoStk(flightUav.Name);
        flightUav.SetFlightDefaults();
        PlayScenario();
    }

Update:

So, setting lsbFlightUavs.SelectedIndex = -1 solves the problem. The above method AddFlightUav() is called from a button's OnClick handler in a second form from the main form. How can I call lsbFlightUavs.SelectedIndex = -1 from this second form when the AddFlightUav() method returns? I know I can make the ListBox static, but that seems like bad practice to me.. what would be a more elegant solution?

1
Can you post the code where you assign the DataSource of the BindingSource and ListBox, and where you add a new item? Incidentally, SelectedIndex is an int so it will never be null: it initialises to -1stuartd
@ Stuart Dunkeld, you're right about the SelectedIndex being an int. I will post the code later tonight.wulfgarpro
I have some further discussions here: social.msdn.microsoft.com/Forums/en/winforms/thread/…wulfgarpro

1 Answers

0
votes

Using WinForms, I implemented the Singleton pattern. This enabled me to access the ListBox control from my second form.

Form 1

private static UavControlForm _instance = new UavControlForm();
private UavControlForm()
{
    InitializeComponent();   
}
public static UavControlForm Instance
{
    get { return _instance; }
}
public ListBox FlightUavListBox
{
    get { return lsbFlightUavs; }
}

Form 2

UavControlForm.Instance.FlightUavListBox.SelectedIndex = -1;