首页 > 解决方案 > 无法在 ASP.NET 网络表单中获取所选项目

问题描述

我正在尝试使用 ASP.NET 网络表单制作文件资源管理器。但是当我试图在列表框中获取选定项目时,出现错误:

System.NullReferenceException

我试图在 Winforms 中制作它,并且效果很好。我很困惑。

这是一些网络表单代码:

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;
    }
}

我是网络表单的初学者,这是我的第一个项目。

如果这是一个愚蠢的问题,我很抱歉。

标签: c#asp.net

解决方案


推荐阅读