Toby Person
Toby Person

Reputation: 211

Generating an HTML Table - Row Control

I am writing an application to generate an "Image Summary" of a directory. Image Summary being an HTML document with a table containing the images of that directory. I am attempting to create the HTML document with a StreamWriter. I want each Row (<tr>) to contain 6 images. How can I achieve this? I've searched and can't find a thing that helps.

Upvotes: 1

Views: 325

Answers (3)

Simon Whitehead
Simon Whitehead

Reputation: 65087

Messy example.. but works (I'm assuming you're not doing this from ASP.NET, as the others have assumed, since you're using a StreamWriter):

static void renderHTML(string folder, string outputFile, int imagesPerRow, params string[] extensions) {
        string[] images = Directory.GetFiles(folder);

        using (var sw = new StreamWriter(File.OpenWrite(outputFile))) {
            sw.WriteLine("<!html><head><title>Example</title></head><body><table>");
            int counter = 0;
            sw.Write("<tr>");
            foreach (string image in images.Where(x => extensions.Any(y => x.Contains(y)))) {
                if (counter == imagesPerRow) {
                    sw.Write("</tr>");
                    sw.Write("<tr>");
                    counter = 0;
                }
                sw.Write("<td style=\"border: 1px solid;\">");
                sw.Write(string.Format("<img src=\"{0}\" />", image));
                sw.Write("</td>");

                counter++;
            }
            sw.Write("</tr></table></body></html>");
        }
    }

You can call it like so:

renderHTML(@"C:\folder", @"C:\output.html", 6, new string[] { ".jpg", ".png", ".gif" });

Upvotes: 1

Jeremy Wiggins
Jeremy Wiggins

Reputation: 7299

Easiest way, in my opinion, would be to start with Directory.GetFiles(). This will return a string[] of file paths.

From there, you could bind that collection to a Repeater. See the answer to this question for a slick way to show n number of elements per row. There's also a link to an article in that thread that shows how to do it with a ListView.

Upvotes: 1

Abe Miessler
Abe Miessler

Reputation: 85126

I would use a ListView. Something like this should get you started:

<asp:ListView runat="server" ID="ListView1" DataSourceID="SqlDataSource1">
  <LayoutTemplate>
    <table runat="server" id="table1" >
      <tr runat="server" id="itemPlaceholder" ></tr>
    </table>
  </LayoutTemplate>
  <ItemTemplate>
    <tr runat="server">
      <td runat="server">
        <asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("ImageUrl") %>' />
      </td>
    </tr>
  </ItemTemplate>
</asp:ListView>

This will just create a tr with a single td for every row of data. You would obviously want to create six td's with images instead of just one.

Upvotes: 1

Related Questions