sisisisi
sisisisi

Reputation: 621

C#: ListBox SelectedIndex changes itself when method returns

I have a problem with ListBox in c#(winforms). This ListBox contains the list of files(only pictures) in a specified directory like this:

private ListBox FileList = new ListBox();
private List<string> Directories = new List<string>
{
  @"some path",
  @"some other path",
  @"..."
};
private List<string> Pictures;

private int selectedDirectory = 0;
public int SelectedDirectory
{
  get { return selectedDirectory; }
  set
  {
    //the list of pictures is returned correctly
    Pictures = GetPictures(Directories[value]); 
    selectedDirectory = value;
    EventHandler handler = this.DirectoryChanged;
    // noone who subscribed to the event
    // changes FileList.SelectedItem or FileList.SelectedIndex
    if(handler != null)
      handler(this, EventArgs.Empty);
    this.SelectedPicture = Pictures.Count == 0 ? -1 : 0;
  }


this.DirectoryChanged += (sender, e) =>
{
  FileList.Items.Clear();
  FileList.Items.AddRange(Pictures);
};

private int selectedPicture
public int SelectedPicture
{
  get { return selectedPicture; }
  set
  {
    selectedPicture = value;
    if(value != -1)
      PictureBox1.Load(Pictures[value]);
    FileList.SelectedIndex = value;
  }
}

// after this method returns, FileList.SelectedIndex changes to a random value depending on what Directory was selected before the change
private void MainFormKeyDown(object sender, KeyEventArgs e)
{
  if(e.KeyCode == Keys.NumPad5)
    SelectedDirectory --;
  if(e.KeyCode == Keys.NumPad2)
    SelectedDirectory ++;
} // the value of SelectedIndex changes after leaving this exact line

I tried to debug it and the result was that from setting the value of FileList.SelectedIndex in this.SelectedPicture it remained 0 until MainFormKeyDown returned. EDIT: I forgot to mention that at that point FileList.SelectedIndex changes to a random value instead of 0 or -1 as it should.

What can cause this kind of behaviour and how can I solve it?

I have checked if I change the value anywhere else in the code or in any event subscription but not.

I also tried using ListView, but the result remained the same.

Now I'm out of ideas.

Upvotes: 0

Views: 276

Answers (1)

kmcnamee
kmcnamee

Reputation: 5255

If the listbox has focus it could be that the KeyDown event fires the user lets go of the key and the KeyUp event fires and the list box changes its selectedIndex. Did you try changing to the KeyUp event and setting

e.Handled = true;

Handled Property

If i hold down the key KeyDown will fire a few times. You can put a Debug.WriteLine to see this if you hold down a key it will fire a few times. Another reason to use KeyUp.

Upvotes: 1

Related Questions