0

I have a silly error I can't get shot of.

I'm using a string to check the name of folders and their extension types. I'm doing this so I can navigate between folders. This works fine with my first folder selection, however, when I try and click on a second one I get null reference exception.

This is what I have at the moment.

 string clickObject = listBox1.SelectedItem.ToString();
 int index = clickObject .LastIndexOf('.');
 string extension = clickObject .Substring(index + 1, clickObject .Length - index - 1);
  if (extension == "folder")
  {
      // do stuff
   }

After this I simply check the files in my folder.

When I go back to the root of my searchable folder and click on another directory, that is when i get the error and the line string clickObject = listBox1.SelectedItem.ToString(); is highlighted.

At the end of my method where I set this I tried setting clickedObject = null; I tried to remove the string that was contained with clickObject.Remove(0); but the error still persists.

How can I clear the information held in clickedObject so I can overwrite it with new information?

Edit

Sorry forgot to mention when I go back to the root I have a button that calls this method:

 using (var client = new WebClient())
        {
            result = client.DownloadString("http://foo.foo.com/images/getDirectoryList.php");
        }

        string[] names = result.Split('|');
        listBox1.Items.Clear();
        foreach (string name in names)
        {
            listBox1.Items.Add(name);
        }
        listBox1.Update();

        listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);

However, when I click an item in the list box, its the first set of code that gets used and that is in a sepearate method.

4

2 回答 2

1

Not sure if this is a bug.. but I too have come across this before.

The problem is, that SelectedItem isn't always available during the SelectedIndexChanged event.. or sometimes not at all.

The fix is to access the item directly:

string clickObject = listBox1.Items[listBox1.SelectedIndex].ToString();

Also, while you're there.. you can use File.GetExtension method in System.IO to get the extension (instead of doing it yourself):

using System.IO;

string extension = File.GetExtension(clickObject);
于 2013-09-03T22:53:43.837 回答
1

If you are handling the SelectedIndexChanged event you need to cope with it being null as there are cases where it won't be set.

Therefore in your handler you must check that listBox1.SelectedItem is not null before trying to convert it to a string:

if (listBox1.SelectedItem != null)
{
    // Your code
}
于 2013-09-03T22:54:46.070 回答