Kasun Lee

Kasun Lee

  • 1.5k
  • 178
  • 13.1k

Problem after listbox clear()

Nov 14 2017 3:19 AM
Hi
 
I'm getting SelectedIndex value -1 after clearing a Listbox and repopulating it. Below is the code:
 
  1. //..........
  2.         public Process[] processes;  
  3.         private void Form1_Load(object sender, EventArgs e)  
  4.         {  
  5.             EnumProcs();  
  6.         }  
  7.  
  8.         private void EnumProcs(){  
  9.             processes = Process.GetProcesses();  
  10.   
  11.             foreach (Process process in processes)  
  12.             {  
  13.                 //Get whatever attribute for process  
  14.                 listBox_processes.Items.Add(process.ProcessName.ToString());  
  15.                 listBox2.Items.Add(process.HandleCount.ToString());  
  16.             }  
  17.         }  
  18.   
  19.         private void listBox_processes_SelectedIndexChanged(object sender, EventArgs e)  
  20.         {  
  21.             listBox_processes.Items.Clear();  
  22.             processes = null;  
  23.             EnumProcs();  
  24.             Process ProcessCurrent = processes[listBox_processes.SelectedIndex]; // ** I get -1 as SelectedIndex **  
  25. //....... 
 Above, I use EnumProcs() to Enumerate system processes and load their names into a Listbox. After 1st population in Form1_Load(), I call EnumProcs() when ever the user selects an item from the Listbox with the proccess names. In SelectedIndexChanged(), I clear() the Listbox before calling EnumProcs(). But when I click an item in the Listbox, SelectedIndex returns -1, though Listbox item count shows 50+.
 
How to fix this?
 
Thanks.

Answers (3)