C# – Giving Borders to the dynamically added HTML table

chtmlstylesheet

I have a HTML table added dynamically in my Code behind.

I am able to give the entire table a border.

How can I do this for each row? I want to add a border under each row.

How can I add a hyperlink to cells at runtime?

What I have tried is

tdr.Width = "100px";
tdr.Attributes.Add("class", "float-left");

row = new HtmlTableRow(); 
cell = new HtmlTableCell();
cell.InnerText = doc;
row.Cells.Add(cell);
tdr.Rows.Add(row);

row = new HtmlTableRow(); 
cell = new HtmlTableCell();
cell.InnerText = "No Timming";
row.Cells.Add(cell);
tdr.Rows.Add(row);

row = new HtmlTableRow(); 
cell = new HtmlTableCell();
cell.InnerText = weekday[i];
row.Cells.Add(cell);
tdr.Rows.Add(row);

And my CSS:

<style type="text/css">
    .float-left
    {
        float:left;
        border-style:solid;
        border-width:2px;
        border-color:Black;
    }
</style>

Best Answer

For the first part of your question, you can add the borders without changing your markup generation by adding a simple css rule:

tr {
  border-bottom: solid 1px black;
} 

There is an overview about styling tables in general via both about.com and w3c schools

Note that you'll also need to set the border-collapse: collapse; css attribute on the table.

I've put an example jsFiddle up for you.

You can place the CSS rule in your CSS section (note I've also added the border-collapse):

<style type="text/css">

    tr {
      border-bottom: solid 1px black;
    } 

    .float-left{
        float:left;
        border-style:solid;
        border-width:2px;
        border-color:Black;
        border-collapse: collapse;
    }

</style>

You could also consider removing the float-left css attribute and just change .float-left to be table to further simplify your code.

For the second part of your question:

and add a hyperlink to each of the values in the table at run time

You can simply use the HtmlAnchorClass.

In effect, a simple example is:

HtmlAnchor htmlanchor = new HtmlAnchor();
htmlanchor.HRef = "http://www.linkurl.com";
htmlanchor.InnerText = "My Link Text";
//Add it to a cell
cell.Controls.Add(htmlanchor);

This will add a hyperlink to your cell.

You may also want to consider using the ASP Repeater Control or the DataGrid control as each of these give you the option to template your markup.