0

I'm trying to make a file explorer with ASP.NET webforms. But when I tried to get selected item in list box, I get an error:

System.NullReferenceException

I tried to make it in Winforms, and it just worked perfectly. I am confused.

Here's some webforms code:

public partial class Default : System.Web.UI.Page
{
    DriveInfo[] drives;
    string path = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        ListBox1.Items.Clear();
        drives = DriveInfo.GetDrives();

        foreach (DriveInfo d in drives)
        {
            ListBox1.Items.Add(d.Name);
        }
    }

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        // this is the error section
        path = ListBox1.SelectedItem.ToString();            
        
        ListBox1.Items.Clear();
        string[] dirs = Directory.GetDirectories(path);
        string[] files = Directory.GetFiles(path);

        foreach(string d in dirs)
        {
            ListBox1.Items.Add(d);
        }

        foreach(string f in files)
        {
            ListBox1.Items.Add(f);
        }

        TextBox1.Text = path;
    }
}

I am a beginner in webforms, and this is my first project.

I am sorry if this is a stupid question.

  • `ListBox1.SelectedItem` is `null`. – mjwills Oct 10 '20 at 10:32
  • Yes, but why? I still get the exception though I have selected an item. – Richard Matthew Oct 10 '20 at 11:45
  • You'd need to share a [mcve]. But for now, check whether `SelectedItem` is `null` before `ToString`ing it. – mjwills Oct 10 '20 at 12:12
  • 95% chance that `ListBox1.Items.Clear();` is to blame - you are removing all of the entries _before_ the button click is processed (put breakpoints on the line of code and you'll see what I mean). As a side effect this will set `SelectedItem` to `null`. You need to check `IsPostBack`. – mjwills Oct 10 '20 at 12:13

0 Answers0