1

I have a website with an image gallery. I want to dynamically add the pictures to the gallery. I have this code:

string[] files = Directory.GetFiles(Server.MapPath(@"images\gallery\projects"));
string temp = files[0];

for (int i = 1; i < files.Length; i++)
{
    HyperLink hp = new HyperLink();

    hp.ImageUrl = "images/gallery/projects/" + Path.GetFileName(files[i]);
    hp.NavigateUrl = "images/gallery/projects/" + Path.GetFileName(temp);
    Panel1.Controls.Add(hp);
    temp = files[i];
}

That iterates the folder with pictures and generates link tag but its not what I need. I am trying to generate this tag:

<a href="images/gallery/picture_fullsize.jpg" 
   title="Caption for picture goes here">
    <img src="images/gallery/picture_thumbnail.jpg"/>
</a>

Any pointers or solution would be much appreciated.

3 Answers 3

2

Your existing method is great which is strongly type, and less error prone than creating a link by yourself.

If you want to add title to a tag, you can use Attributes.Add method.

var hp = new HyperLink();
hp.ImageUrl = "images/gallery/projects/" + Path.GetFileName(files[i]);
hp.NavigateUrl = "images/gallery/projects/" + Path.GetFileName(temp);
hp.Attributes.Add("title", "Caption for picture goes here");
Panel1.Controls.Add(hp);
Sign up to request clarification or add additional context in comments.

Comments

2

I would recommend that you instead solve this using a template control like a repeater. Seems like you're already set up to do that given that you're working with a list that can act as your bound datasource. Dynamically creating html should be avoided when possible.

See more here:

http://msdn.microsoft.com/en-us/library/zzx23804(v=vs.85).aspx

Comments

1

Use HtmlTextWriter. It allows you to create nice clean HTML, and can easily do nested tags like what you want. So your code would look something like this:

StringWriter stringWriter = new StringWriter();

using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter)) //Always enclose in 'using' for cleaner code
for (int i = 1; i < files.Length; i++)
{
    //Write the starting 'a' tag
    writer.AddAttribute(HtmlTextWriterAttribute.Href, "images/gallery/projects/" + Path.GetFileName(temp));
    writer.RenderBeginTag(HtmlTextWriterTag.A); 

    //Write the starting 'img' tag
    writer.AddAttribute(HtmlTextWriterAttribute.Src, "images/gallery/projects/" + Path.GetFileName(files[i]));
    writer.RenderBeginTag(HtmlTextWriterTag.Img);

    //Close the 'img' tag
    writer.RenderEndTag();

    //Close the 'a' tag
    writer.RenderEndTag();  
}

var generatedHtml = stringWriter.ToString(); //The final HTML

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.