简体   繁体   中英

How to view selected item in listbox in image viewer asp.net

I have this code that populates my listbox that contains what I type in the textbox. My problem is how can I view the selected item in my listbox in a image viewer since all my files are images? Am I missing something?

Here's my code:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM