0

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

这是我的代码:

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();
        }
4

1 回答 1

2

This should work I think:

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

In this part, you need to not only have the file name, but also the path where the file was found. In my sample, the sub path where the file was found is first set into subPath and that is then stored as the value for the list item.

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

Here we use the sub path to set the correct url to the image.

Note that you need to have the AutoPostBack set to true on the DocumentImage in your asxp page in order for the image to change when you change the selection in the list box.

于 2014-09-19T07:48:37.563 回答