C# 如何在image viewer asp.net中查看列表框中的选定项

C# 如何在image viewer asp.net中查看列表框中的选定项,c#,asp.net,listbox,getfiles,image-viewer,C#,Asp.net,Listbox,Getfiles,Image Viewer,我有这段代码填充我的列表框,其中包含我在文本框中键入的内容。我的问题是,既然我的所有文件都是图像,我如何在图像查看器中查看我的列表框中的选定项目?我错过什么了吗 这是我的密码: protected void Button1_Click(object sender, EventArgs e) { ListBox1.Items.Clear(); string[] files = Directory.GetFiles(Server.MapPath("~/imag

我有这段代码填充我的列表框,其中包含我在文本框中键入的内容。我的问题是,既然我的所有文件都是图像,我如何在
图像查看器中查看我的
列表框中的选定项目?我错过什么了吗

这是我的密码:

protected void Button1_Click(object sender, EventArgs e)
    {
        ListBox1.Items.Clear();
        string[] files = Directory.GetFiles(Server.MapPath("~/images"), "*.*", SearchOption.AllDirectories);


        foreach (string item in files)
        {
            string fileName = Path.GetFileName(item);
            if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
            {
                ListBox1.Items.Add(fileName);
            }

        }
    }

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            DocumentImage.ImageUrl = Directory.GetDirectories("~/images") + ListBox1.SelectedItem.ToString();
        }

我认为这应该行得通:

protected void Button1_Click(object sender, EventArgs e)
{
    ListBox1.Items.Clear();
    string[] files = Directory.GetFiles(Server.MapPath("~/images"), "*.*", SearchOption.AllDirectories);
    foreach (string item in files)
    {
        string fileName = Path.GetFileName(item);
        if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
        {
            string subPath = item.Substring(Server.MapPath("~/images").Length).Replace("\\","/");
            ListBox1.Items.Add(new ListItem(fileName, subPath));
        }
    }
}
在本部分中,您不仅需要文件名,还需要找到文件的路径。在我的示例中,找到文件的子路径首先设置为
subPath
,然后存储为列表项的值

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    DocumentImage.ImageUrl = "~/images" + ListBox1.SelectedItem.Value;
}
在这里,我们使用子路径为图像设置正确的url


请注意,您需要在
asxp
页面中的
DocumentImage
上将
AutoPostBack
设置为true,以便在更改列表框中的选择时更改图像。

Directory.GetDirectories(~/images)返回数组,因此您实际上是在尝试将数组与字符串组合(String[]+String)。@JuStDaN那我该怎么办?