NatsuDragneel
NatsuDragneel

Reputation: 317

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

Upvotes: 0

Views: 1773

Answers (1)

user1429080
user1429080

Reputation: 9166

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.

Upvotes: 2

Related Questions