Wednesday, December 12, 2012

Create Dynamic HTML Table in ASP.NET


First let us create a sample DataTable to retrieving the data for display in the HTML table.

private DataTable createBindDatatable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Country", typeof(string));
        dt.Columns.Add("Nationality", typeof(string));

        dt.Rows.Add("Chamara", "Sri lanaka", "Sri lanakan");
        dt.Rows.Add("Sam", "America","American");
        dt.Rows.Add("Jhon", "India","Indian");
        dt.Rows.Add("Cater", "Pakistan","Pakistani");
        dt.Rows.Add("Amanda", "Australia", "Australian");
        return dt;
    }

Now we are going to use the StringBuilder class for creating our dynamic table and loop through the data table in order to add the cell content of the table.

private void DynamicHTMLTable()

    {
        StringBuilder sbTable = new StringBuilder();
        sbTable.Append("<table border='1'>");

        sbTable.Append("<tr style='font-weight: bold'>"); // This is the header row.
        sbTable.Append("<td>");
        sbTable.Append("&nbsp;Name");
        sbTable.Append("</td>");
        sbTable.Append("<td>");
        sbTable.Append("&nbsp;Country");
        sbTable.Append("</td>");
        sbTable.Append("<td>");
        sbTable.Append("&nbsp;Nationality");
        sbTable.Append("</td>");
        sbTable.Append("</tr>");

        foreach (DataRow item in createBindDatatable().Rows)
        {
            sbTable.Append("<tr>");
            sbTable.Append("<td>");
            sbTable.Append("&nbsp;"+item["Name"].ToString());
            sbTable.Append("</td>");
            sbTable.Append("<td>");
            sbTable.Append("&nbsp;"+item["Country"].ToString());
            sbTable.Append("</td>");
            sbTable.Append("<td>");
            sbTable.Append("&nbsp;" + item["Nationality"].ToString());
            sbTable.Append("</td>");
            sbTable.Append("</tr>");
        }

        sbTable.Append("</table>");

        Response.Write(sbTable.ToString());
    }



No comments:
Write comments
Recommended Posts × +