Step 1:- Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Demo.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGenTable" runat="server" Text="Generate
Table" OnClick="btnGenTable_Click" />
<br />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
Step 2:- Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Demo
{
public partial class Default:
System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
else
{
if (Page.IsPostBack)
{
if (Session["DynTable"] != null)
PlaceHolder1.Controls.Add(new Literal {
Text = Session["DynTable"].ToString()
});
}
}
}
protected DataTable DynamicTable()
{
DataTable dt
= new DataTable();
DataRow dr
= null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
int totalRow
= 5;
for (int i
= 0; i < totalRow; i++)
{
dr
= dt.NewRow();
dr["RowNumber"] = i
+ 1;
dr["Column1"] = "Row" +
i;
dr["Column2"] = "Row" +
i;
dr["Column3"] = "Row" +
i;
dt.Rows.Add(dr);
}
Session["DynTable"] =
dt;
return dt;
}
protected void btnGenTable_Click(object sender, EventArgs e)
{
StringBuilder sb
= new StringBuilder();
sb.AppendLine("<table
border=\"1\">");
DataTable dt
= DynamicTable();
if (dt.Rows.Count
> 0)
{
//
Table Header Name
sb.AppendLine("<tr>");
for (int col
= 0; col < dt.Columns.Count; col++)
{
sb.AppendLine("<td>" +
dt.Columns[col].ColumnName + "</td>");
}
sb.AppendLine("</tr>");
//
Table Row details
for (int row
= 0; row < dt.Rows.Count; row++)
{
sb.AppendLine("<tr>");
for (int col
= 0; col < dt.Columns.Count; col++)
{
sb.AppendLine("<td>" +
dt.Rows[row][col] + "</td>");
}
sb.AppendLine("</tr>");
}
}
sb.AppendLine("</table>");
PlaceHolder1.Controls.Add(new Literal {
Text = sb.ToString() });
}
}
}
Note:-
Dynamically generated table loss during post back, If page
participating multiple post back.
To solve
it, recreate dynamic table during each post back on page load.
No comments:
Post a Comment