Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

ASP.NET C# - Dynamically adding table rows & cells issue.

Posted on 2009-07-01
7
Medium Priority
?
6,183 Views
Last Modified: 2013-12-17
I'm trying to click a linkbutton and have more rows added to a table via server side code. I will adding controls that I can iterate through later.  Every time the link button it clicked, I want another NEW row to be added.  However, when clicked...  one new row is added, but that's it. When clicked again, it seems that the row is that is just added is lost and the same row is re-added.   ViewState not being enabled doesn't seem to be the problem, as I have it enabled ever where I can think of.  Maybe my understanding of how postback and viewstate works is incorrect. I would expect that when you have a session on the server and viewstate enabled that when a control is dynamically added via postback, it would persist until you leave the page.  Anyone have any ideas? I'm sure someone has come across this before.
<%@ Page Language="C#" EnableViewState="true" EnableSessionState="True" AutoEventWireup="true" CodeFile="ajaxtest.aspx.cs" Inherits="ajaxtest" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    
    <form id="form1" runat="server" enableviewstate="true">
  
        <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
        <asp:Table runat="server" ID="MyTable" EnableViewState="true">
            <asp:TableRow>
                <asp:TableCell>
                Exsisting Row
                </asp:TableCell>
            </asp:TableRow>
        </asp:Table>
        
        
    
    </form>
</body>
</html>
 
 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
 
public partial class ajaxtest : System.Web.UI.Page
{    
    int Counter = 0;
 
    protected void Page_Load(object sender, EventArgs e)
    {
        
 
    }
 
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        TableCell NewCell = new TableCell();
        TableRow NewRow = new TableRow();
 
        Counter++; 
        NewCell.Text = "Dynamically Added " + Counter.ToString();
        
        NewRow.Cells.Add(NewCell);
        MyTable.Rows.Add(NewRow);
    }
}

Open in new window

0
Comment
Question by:orrsafety
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 41

Expert Comment

by:Kyle Abrahams
ID: 24754965
After the rows.Add

MyTable.DataBind();

DataBind syncs up the changes.
0
 

Author Comment

by:orrsafety
ID: 24755029
I gave that a shot, but that didn't do it. I'm still only getting one new row. Also to clarify, this is not a "gridview" and I'm not working with any data that's getting bound.  Thanks for time and suggestion.
0
 

Author Comment

by:orrsafety
ID: 24755124
I'm working with the .net 2.0 framework, I tried with 3.5 as well and I'm still getting the same issue.  Don't know if that helps?
0
Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

 
LVL 13

Accepted Solution

by:
crazyman earned 2000 total points
ID: 24755365
Dynamically created controls must be re-created on each postback see : http://www.singingeels.com/Articles/Dynamically_Created_Controls_in_ASPNET.aspx

Since you add the table row and then next postback you dont re-add the one you already added, it wont get re-created.

You could create list held in view state, something like :

public List<string> Items
{
                get {return this.ViewState["Items"] ?? new List<string>();
                set {this.ViewState["Items"] = value;
}

then in your button click do something like

List<string> lst = this.Items;
lst.Add("New Item");
this.Items = lst;

then override CreateChildControls and do something like

foreach (string str in this.Items)
{
TableCell NewCell = new TableCell();
        TableRow NewRow = new TableRow();
        NewCell.Text = String.Format("Added Cell {0}",str);        
        NewRow.Cells.Add(NewCell);
        MyTable.Rows.Add(NewRow);

}
0
 
LVL 13

Expert Comment

by:crazyman
ID: 24755527
This works ok for me

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
        <asp:Table runat="server" ID="MyTable" EnableViewState="true">
            <asp:TableRow>
                <asp:TableCell>
                Exsisting Row
                </asp:TableCell>
            </asp:TableRow>
        </asp:Table>
 
    </form>
</body>
</html>
=============================================================CODEBEHIND
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class Test : System.Web.UI.Page
{
    public List<string> Items
    {
        get { return (List<string>)this.ViewState["Items"] ?? new List<string>(); }
        set {this.ViewState["Items"] = value;}
    }
 
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        string txt = DateTime.Now.ToString();
        List<string> lst = this.Items;
        lst.Add(txt);
        this.Items = lst;
        RenderTableItem(txt);
 
    }
 
    protected override void CreateChildControls()
    {
        //Save any existing that were added via markup
        RenderTable();
    }
 
    private void RenderTable()
    {
        foreach (string str in this.Items)
        {
            RenderTableItem(str);
        }
    }
    private void RenderTableItem(string str)
    {
        TableCell NewCell = new TableCell();
        TableRow NewRow = new TableRow();
        NewCell.Text = String.Format("Added Cell {0}", str);
        NewRow.Cells.Add(NewCell);
        MyTable.Rows.Add(NewRow);
    }
 
}

Open in new window

0
 

Author Comment

by:orrsafety
ID: 24755717
Well I think this certainly puts me on the right track.  I wasn't aware of that process.  Thank you very much!
0
 

Author Comment

by:orrsafety
ID: 24755929
Since I was only concerned with a single table. This is what I ended up doing.  I saved the table to a session variable session variable which is nice cause it saves everything in the table. I set a temp table to the session saved table or if that doesn't exists to the table on the page. I make all the modifications to that, then place it back in the page and save to the session variable. This works exactly like I wanted it to.
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">LinkButton</asp:LinkButton>
        
        <asp:Panel ID="TableContainer" runat="server">
            <asp:Table ID="TableOnThePage" runat="server">
                <asp:TableRow>
                    <asp:TableCell>Exsisting Row</asp:TableCell>
                </asp:TableRow>
            </asp:Table>
        </asp:Panel>
    </div>
    </form>
</body>
</html>
 
=====================================================================
 
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
 
public partial class _Default : System.Web.UI.Page 
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            if (Session["PersistentTable"] != null)
            {
                TableContainer.Controls.Remove(TableOnThePage);
                TableContainer.Controls.Add((Table)Session["PersistentTable"]);
            }
        }
        else
        {
            if (Session["PersistentTable"] != null) Session["PersistentTable"] = null;
        }
    }
 
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Table TempTable = new Table();
        if (Session["PersistentTable"] != null) TempTable = (Table)Session["PersistentTable"];
        else TempTable = TableOnThePage; 
        
 
        TableCell NewCell = new TableCell();
        TableRow NewRow = new TableRow();
 
        NewCell.Text = "Dynamically Added " + TempTable.Rows.Count.ToString();
 
        NewRow.Cells.Add(NewCell);
        TempTable.Rows.Add(NewRow);
 
        TableContainer.Controls.Remove(TableOnThePage);
        TableContainer.Controls.Add(TempTable);
        Session["PersistentTable"] = TempTable;
        
    }
}

Open in new window

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

610 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question