Thread: Problem after listbox clear()

  1. #1
    Android geek@02's Avatar
    Join Date
    Mar 2004
    Location
    Kurunegala Colony, Sri Lanka, Sri Lanka
    Posts
    470

    Problem after listbox clear()

    Hi

    I'm getting SelectedIndex value -1 after clearing a Listbox and repopulating it. Below is the code:

    Code:
    • //..........
    • public Process[] processes;
    • private void Form1_Load(object sender, EventArgs e)
    • {
    • EnumProcs();
    • }
    • private void EnumProcs(){
    • processes = Process.GetProcesses();
    • foreach (Process process in processes)
    • {
    • //Get whatever attribute for process
    • listBox_processes.Items.Add(process.ProcessName.ToString());
    • listBox2.Items.Add(process.HandleCount.ToString());
    • }
    • }
    • private void listBox_processes_SelectedIndexChanged(object sender, EventArgs e)
    • {
    • listBox_processes.Items.Clear();
    • processes = null;
    • EnumProcs();
    • Process ProcessCurrent = processes [listBox_processes.SelectedIndex]; // ** I get -1 as SelectedIndex **
    • //.......

    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.
    GameJolt: https://gamejolt.com/@KasunL
    Game Development Youtube:
    https://is.gd/XyhYoP
    Amateur IT Blog: http://everything-geeky.blogspot.com/



    (and, sorry for my amateur English)

  2. #2
    Registered User
    Join Date
    Jun 2017
    Posts
    157
    The problem is when
    listBox_processes_SelectedIndexChanged is called you delete all items and SelectedIndex becomes -1.
    When you fill the listbox again SelectedIndex is still -1.

    Why do you delete it and fill it again? Do you think the processes have changed?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. listbox Problem
    By emtec in forum C++ Programming
    Replies: 2
    Last Post: 04-27-2010, 12:59 AM
  2. listbox double click problem
    By mr_empty in forum C# Programming
    Replies: 0
    Last Post: 06-11-2008, 03:26 AM
  3. Problem with Listbox and Subclassing
    By KonArtis in forum Windows Programming
    Replies: 3
    Last Post: 10-20-2004, 05:47 AM
  4. Radiobuttons and listbox problem
    By osal in forum Windows Programming
    Replies: 2
    Last Post: 08-02-2004, 11:43 AM
  5. Problem with file listbox
    By Garfield in forum Windows Programming
    Replies: 6
    Last Post: 02-04-2002, 03:41 PM

Tags for this Thread