Quote:
I have created a dynamic table using Asp.net with c#. Now I want to store this dynamically created table in the session, How can i do that?
You don't store the HTML Table in Session. Instead you will store the rows and columns count from your Table so you can recreate your Table on each and every postbacks based from the previous rows and columns count. Here's a quick example:
ASPX:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dynamic Adding of Rows in ASP Table Demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add New Row" />
</form>
</body>
</html>
CODE BEHIND:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default1 : System.Web.UI.Page
{
private int numOfRows = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack){
GenerateTable(numOfRows);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["RowsCount"] != null)
{
numOfRows = Convert.ToInt32(Session["RowsCount"].ToString());
GenerateTable(numOfRows);
}
}
private void SetPreviousData(int rowsCount, int colsCount)
{
Table table = (Table)Page.FindControl("Table1");
if (table != null)
{
for (int i = 0; i < rowsCount; i++)
{
for (int j = 0; j < colsCount; j++)
{
TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
}
}
}
}
private void GenerateTable(int rowsCount)
{
Table table = new Table();
table.ID = "Table1";
Page.Form.Controls.Add(table);
const int colsCount = 3;
for (int i = 0; i < rowsCount; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < colsCount; j++)
{
TableCell cell = new TableCell();
cell.ColumnSpan = colsCount;
TextBox tb = new TextBox();
tb.ID = "TextBoxRow_" + i + "Col_" + j;
cell.Controls.Add(tb);
row.Cells.Add(cell);
}
table.Rows.Add(row);
}
SetPreviousData(rowsCount, colsCount);
rowsCount++;
Session["RowsCount"] = rowsCount;
}
}