Dynamically modifying Table

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • roopesh
    New Member
    • Jul 2006
    • 8

    Dynamically modifying Table

    Hi

    I am a newbee in asp.net. I want to create a table dynamically. Say there are two buttons 'add row', 'delete row' which calls addRow, deleteRow event handlers. A sample code is given below :

    Problem here is when the page is postback, pageLoad is called and the Page doesnt have the updated table information. So addRow doesn't work (row.count will always return 0).

    How to solve this problem? I read that ControlState can be used to save states across postbacks. Can I use ControlState? If so, can you please give me an example code.

    protected void addRow(object sender, EventArgs e)
    {
    int count2 = table2.Rows.Cou nt;
    TableRow r = new TableRow();
    TableCell c = new TableCell();

    CheckBox ck = new CheckBox();
    c.Controls.Add( ck);
    r.Cells.Add(c);
    int count = table2.Rows.Cou nt;
    table2.Rows.Add (r);
    count = table2.Rows.Cou nt;
    //throw new Exception("The method or operation is not implemented.");
    }

    protected void Page_Load(objec t sender, EventArgs e)
    {

    }

    Thanks and Regards
    Roopesh
  • roopesh
    New Member
    • Jul 2006
    • 8

    #2
    Hi
    I have modified the code a little bit. Now I store the modified table object in a session. When each postback happens the table object is updated from the session object.

    Now the problem is after the first addition further additions are not visible and it erases the checkbox (row) added initially.

    Is this a prefered approach?

    protected void addRow(object sender, EventArgs e)
    {
    int count2 = table2.Rows.Cou nt;
    TableRow r = new TableRow();
    TableCell c = new TableCell();

    CheckBox ck = new CheckBox();
    c.Controls.Add( ck);
    r.Cells.Add(c);
    int count = table2.Rows.Cou nt;
    table2.Rows.Add (r);
    count = table2.Rows.Cou nt;

    Session["table2"] = table2;
    }

    protected void Page_Load(objec t sender, EventArgs e)
    {
    if (IsPostBack)
    {
    Table table = (Table)Session["table2"];

    if(table!=null) {
    table2 = table;
    }
    }
    }

    (Do I need to clone the table?).

    Thanks and regards
    Roopesh
    Last edited by roopesh; Jul 19 '06, 03:21 AM.

    Comment

    • coldflame
      New Member
      • Jul 2006
      • 19

      #3
      Hi,

      You have to perform the table creation on the load event of the Page. Because if you did't perform the table creation or any addition of controls on the page, it will not remain next time you load the page, the same thing is happening to you .

      Please fell free to ask if you have any Problem or if you really need a code.

      Comment

      • roopesh
        New Member
        • Jul 2006
        • 8

        #4
        Originally posted by coldflame
        Hi,

        You have to perform the table creation on the load event of the Page. Because if you did't perform the table creation or any addition of controls on the page, it will not remain next time you load the page, the same thing is happening to you .

        Please fell free to ask if you have any Problem or if you really need a code.
        But what if we need to dynamically modify the table like adding a row to the table. The code to add will occur in the some event handler not in the page_load event right? This is where I am getting stuck.

        I have also tried generating the table from the database each time when the page load happens. So, what appears to me logically is that the table should always have the recent state. But it is not happening.

        Can you please tell me why this is happening. Any piece of code that will help me understand will be very helpful.

        Thanks and Regards
        Roopesh

        Comment

        • coldflame
          New Member
          • Jul 2006
          • 19

          #5
          Originally posted by roopesh
          But what if we need to dynamically modify the table like adding a row to the table. The code to add will occur in the some event handler not in the page_load event right? This is where I am getting stuck.

          I have also tried generating the table from the database each time when the page load happens. So, what appears to me logically is that the table should always have the recent state. But it is not happening.

          Can you please tell me why this is happening. Any piece of code that will help me understand will be very helpful.

          Thanks and Regards
          Roopesh
          Hi

          Can you please give me the code, i will guide you according to your requirement.

          Regards

          Comment

          • roopesh
            New Member
            • Jul 2006
            • 8

            #6
            Code is a bit long :( I am trying to create a task manager. One can add tasks. Tasks can be pending tasks and completed tasks. For this purpose I have used two Tables - pending_table and completed_table . In the pending_table, each Task is represented by a CheckBox, TextBox (task desc) and an Edit button. When we click on CheckBox the row should get removed from pending_table and get added to completed_table and vice versa.
            Problem I face is that, when I try to click pending list. It works for the first time. But fails when I click another row second time. (When clicked, from the ID of the checkbox I extracts the index of the clicked row. From the row I retrieves the TaskId stored in a hidden field. The error that happens over here is that the TaskId that I get is the taskId of the row which I clicked the first time (Now the row should not be there in that clicked table. Hope I have written clearly. What I am not getting is that whether this is a problem associated with the postback issue or some other bug in my program.
            -----
            protected void Page_Load(objec t sender, EventArgs e) {
            populatePending Tasks();
            populateComplet edTasks();
            }

            protected void populatePending Tasks() {
            //connect_to_db_g et_the_pending_ tasks_against_p articular_id
            string userId = "roopesh";
            //TaskComponent is a class used for database interaction, update, delete,insert tasks etc.
            TaskComponent taskComp = new TaskComponent() ;
            List<Task> tasks = new List<Task>();
            tasks = taskComp.GetPen dingTasks(userI d);
            Session["pendingTas ks"] = tasks;

            int row_cnt = tasks.Count;
            int col_cnt = 4;

            for (int i = 0; i < row_cnt; i++ ){
            TableRow row = new TableRow();
            for (int j = 0; j < col_cnt; j++){
            TableCell cell = new TableCell();
            if (j == 0){
            CheckBox chk = new CheckBox();
            chk.ID = "unchecked" + i;
            chk.AutoPostBac k = true;
            chk.CheckedChan ged += new
            EventHandler(mo veToCompleteHan dler);
            cell.Controls.A dd(chk);
            }
            if (j == 1){
            TextBox t = new TextBox();
            t.ID = "text1" + i;
            t.Text = tasks[i].Desc;
            t.Width = 200;
            cell.Controls.A dd(t);
            }
            if (j == 2){
            LinkButton lnk = new LinkButton();
            lnk.ID = "edit1" + i;
            lnk.Text = "Edit" + i;
            cell.Controls.A dd(lnk);

            }
            if(j == 3){
            HiddenField h = new HiddenField();
            h.ID = "hidden" + i;
            h.Value = tasks[i].Id;
            cell.Controls.A dd(h);
            }
            row.Cells.Add(c ell);
            }
            pending_table.R ows.Add(row);
            }
            //Session["pending_ta ble"] = pending_table;
            }

            void moveToCompleteH andler(object sender, EventArgs e)
            {
            //I am using the id of the clicked checkbox to get the index of the row.

            string id = ((System.Web.UI .WebControls.Ch eckBox)sender). ID;
            int index = getIndex(id, pending_table,1 );

            //Hidden field has taskId which is unique for each task in database

            HiddenField c =
            (HiddenField)pe nding_table.Row s[index].Cells[1].FindControl("h idden" +
            index);
            string taskId = c.Value;

            string uId = "roopesh";
            TaskComponent comp = new TaskComponent() ;
            List<Task> ts = new List<Task>();

            //returns all the pending tasks from the database
            ts = comp.GetPending Tasks(uId);
            Session["pendingTas ks"] = ts;

            List<Task> tasks = (List<Task>)Ses sion["pendingTas ks"];

            //finding the task in the clicked row. Then modify the task object
            //and is send back to the database

            Task task = getPendingTask( tasks,taskId);

            DateTime compDate = task.compDate;
            DateTime subDate = task.subDate;
            task.compDate = DateTime.Now;
            task.modDate = DateTime.Now;
            DateTime modDate = task.modDate;
            String desc = task.Desc ;

            String userId = task.uId;
            TaskComponent taskComp = new TaskComponent() ;

            taskComp.Update Task(task);

            TableRow row_u = pending_table.R ows[index];

            //removing the row and adding it to completed Table

            pending_table.R ows.Remove(pend ing_table.Rows[index]);
            completed_table .Rows.Add(row_u );

            List<Task> tss = new List<Task>();
            tss = comp.GetPending Tasks(uId);
            Session["pendingTas ks"] = tss;

            //string userId = "roopesh";
            comp = new TaskComponent() ;
            List<Task> tks = new List<Task>();
            tks = comp.GetComplet edTasks(uId);
            Session["completedTasks "] = tks;

            }

            protected void populateComplet edTasks()
            {
            //connect_to_db_g et_the_complete d_tasks_against _particular_id
            //get the session id from session object
            string userId = "roopesh";
            TaskComponent taskComp = new TaskComponent() ;
            List<Task> tasks = new List<Task>();
            tasks = taskComp.GetCom pletedTasks(use rId);
            Session["completedTasks "] = tasks;
            int row_cnt = tasks.Count;
            int col_cnt = 4;
            for (int i = 0; i < row_cnt; i++)
            {
            TableRow row = new TableRow();
            for (int j = 0; j < col_cnt; j++)
            {
            TableCell cell = new TableCell();

            if (j == 0)
            {
            CheckBox chk = new CheckBox();
            chk.ID = "checked" + i;
            chk.AutoPostBac k = true;
            chk.Checked=tru e;
            chk.CheckedChan ged += new
            EventHandler(mo veToPendingHand ler);
            cell.Controls.A dd(chk);
            }
            if (j == 1)
            {
            TextBox t = new TextBox();
            t.ID = "text2" + i;
            t.Text = tasks[i].Desc;
            t.Width = 200;
            cell.Controls.A dd(t);
            }
            if (j == 2)
            {
            LinkButton lnk = new LinkButton();
            lnk.ID = "edit2" + i;
            lnk.Text = "Edit" + i;
            cell.Controls.A dd(lnk);
            lnk.Visible = false;
            }
            if (j == 3)
            {
            HiddenField h = new HiddenField();
            h.ID = "hidden2" + i;
            h.Value = tasks[i].Id;
            cell.Controls.A dd(h);
            }
            row.Cells.Add(c ell);
            } completed_table .Rows.Add(row);
            }
            Session["completed_tabl e"] = completed_table ;
            }

            void moveToPendingHa ndler(object sender, EventArgs e)
            {
            completed_table = (Table)Session["completed_tabl e"];
            string id = ((System.Web.UI .WebControls.Ch eckBox)sender). ID;

            //int index = getIndex(id, completed_table , 2);
            int index = getIndex(id, completed_table , 2);
            HiddenField c =
            (HiddenField)co mpleted_table.R ows[index].Cells[1].FindControl("h idden2"
            + index);
            string taskId = c.Value;

            string uId = "roopesh";
            TaskComponent comp = new TaskComponent() ;
            List<Task> tks = new List<Task>();
            tks = comp.GetComplet edTasks(uId);
            Session["completedTasks "] = tks;

            List<Task> tasks = (List<Task>)Ses sion["completedTasks "];

            Task task = getPendingTask( tasks, taskId);
            DateTime compDate = task.compDate;
            DateTime subDate = task.subDate;
            task.compDate = DateTime.MinVal ue;
            task.modDate = DateTime.Now;
            DateTime modDate = task.modDate;
            String desc = task.Desc;

            String userId = task.uId;
            TaskComponent taskComp = new TaskComponent() ;
            taskComp.Update Task(task);

            TableRow row_u = completed_table .Rows[index];
            completed_table .Rows.Remove(co mpleted_table.R ows[index]);
            pending_table.R ows.Add(row_u);

            Session["completed_tabl e"] = completed_table ;
            Session["pending_ta ble"] = pending_table;
            List<Task> ts = new List<Task>();
            ts = taskComp.GetPen dingTasks(uId);
            Session["pendingTas ks"] = ts;

            //string userId = "roopesh";
            comp = new TaskComponent() ;
            List<Task> tkss = new List<Task>();
            tkss = comp.GetComplet edTasks(uId);
            Session["completedTasks "] = tkss;
            }

            int getIndex(string id, Table table, int mode)
            {
            int row_cnt = 0;
            TableRow current_row;
            TableCell current_cell;

            IEnumerator myRowEnum = table.Rows.GetE numerator();
            while (myRowEnum.Move Next())
            {
            IEnumerator myCellEnum = table.Rows[row_cnt].Cells.GetEnume rator();
            while (myCellEnum.Mov eNext())
            {
            current_cell = (TableCell)myCe llEnum.Current;
            CheckBox check = null;
            if(mode == 1)
            check =
            (CheckBox)curre nt_cell.FindCon trol("unchecked "+row_cnt);
            if(mode == 2)
            check =
            (CheckBox)curre nt_cell.FindCon trol("checked"+ row_cnt);

            current_row = (TableRow)myRow Enum.Current;
            int indx = table.Rows.GetR owIndex(current _row);

            if ((check.ID).Equ als(id))
            {
            return indx;
            }
            }
            row_cnt++;
            }
            return -1;
            }
            Task getPendingTask( List<Task> tasks, string taskId){
            for (int i = 0; i < tasks.Count; i++)
            {
            if ((tasks[i].Id).Equals(tas kId))
            {
            return tasks[i];
            }} return null;
            }}
            Last edited by roopesh; Jul 20 '06, 02:15 AM.

            Comment

            • roopesh
              New Member
              • Jul 2006
              • 8

              #7
              Please tell if I need to cut short the code.

              Regards
              Roopesh

              Comment

              • coldflame
                New Member
                • Jul 2006
                • 19

                #8
                Originally posted by roopesh
                Please tell if I need to cut short the code.

                Regards
                Roopesh
                Hi , Sorry for late reply , Caz i was busy a little bit.

                Hmm i have seen a little bit of your good but its too long to read it out.

                So i have made an example for you that will help you how to create and delete rows on dynamically , I used to work in VB Script , not too much changed from c# with respect to function but syntax is changed. hope this will help you

                'Code

                <%@ Page Language="VB" Debug="true"%>
                <script runat="server">

                dim itemtable as table
                dim itemrow as tablerow
                dim itemcell(3) as tablecell
                dim del_btn as button

                public sub page_load(Sende r as object, e as eventargs)

                if not me.ispostback then
                viewstate("cou" ) =2

                end if

                createTable(cty pe(viewstate("c ou"),integer) )
                end sub

                protected sub createTable(cou nt as integer)
                tableplcHld.con trols.clear()
                dim i,c as integer
                itemtable = new table()
                itemtable.width =unit.percentag e(50)
                itemtable.borde rwidth=unit.pix el(2)

                for i=0 to count-1

                del_btn = new button
                del_btn.text="D el"
                del_btn.id="del " & i
                addhandler del_btn.click, addressof del_click

                for c=0 to 2
                itemcell(c) = new tablecell()
                itemcell(c).Hor izontalAlign = HorizontalAlign .left
                itemcell(c).bor derwidth=unit.p ixel(1)
                itemcell(c).wid th=unit.percent age(50)
                if c<>2 then
                itemcell(c).tex t = i & c
                else
                itemcell(c).con trols.add(del_b tn)
                end if
                next
                itemrow = new tablerow
                itemrow.cells.a dd(itemcell(0))
                itemrow.cells.a dd(itemcell(1))
                itemrow.cells.a dd(itemcell(2))
                itemtable.rows. add(itemrow)
                next
                tableplcHld.con trols.add(itemt able)
                end sub

                public sub buttonclick(sen der as object , e as eventargs)
                viewstate("cou" ) =ctype(viewstat e("cou"),intege r)+1
                createTable(cty pe(viewstate("c ou"),integer) )
                end sub

                public sub del_click(sende r as object , e as eventargs)
                viewstate("cou" ) =ctype(viewstat e("cou"),intege r)-1
                createTable(cty pe(viewstate("c ou"),integer) )
                end sub

                </script>
                <html>
                <head>
                </head>
                <body>
                <form runat="server">
                <table>
                <tr>
                <tD>
                <asp:button id="createrows " runat=server onclick="button click" width=80 text="Creat_Row s"/>
                </tD>
                </tR>
                <Tr>
                <td>
                <asp:PlaceHolde r runat="server" id="tableplcHld "> </asp:PlaceHolder >
                </td>
                </tr>
                </table>
                </form>
                </body>
                </html>

                Copy and paste the code in the aspx file and you can see the results.
                Hope this will help you

                Regards.

                Comment

                • roopesh
                  New Member
                  • Jul 2006
                  • 8

                  #9
                  Originally posted by coldflame
                  Hi , Sorry for late reply , Caz i was busy a little bit.

                  Copy and paste the code in the aspx file and you can see the results.
                  Hope this will help you

                  Regards.
                  Thanks a lot for your reply. It is a very nice example. As far as I understand your program keeps a variable in viewstate and recreates the table when ever a requst is made. Can I know whether we can save the state of the table object like this? May be I am asking a foolish question.

                  Apart from that you are not dynamically creating the row in the page_load event, as you have mentioned earlier (to retain the dynamically created rows).

                  Thanks again for the reply

                  Thanks and Regards
                  Roopesh

                  Comment

                  • mady1380
                    New Member
                    • Sep 2006
                    • 18

                    #10
                    hi

                    i am naive in .net i have recently started programming in .net.
                    i want to add rows to my existing table.I am not able to.
                    i am using this code for it..when i run the code, it shows no error...
                    but it doesnt create an extra row in my table.
                    can u plz suggest me why i am not able to see the new row, or why it is not being created.


                    Private Sub btn1_Click(ByVa l sender As System.Object, ByVal e As System.EventArg s) Handles btn1.Click
                    ' Total number of rows
                    Dim rowCnt As Integer
                    '' Current row count
                    Dim rowCtr As Integer
                    '' Total number of cells (columns)
                    Dim cellCtr As Integer
                    '' Current cell counter
                    Dim cellCnt As Integer
                    Dim tcell As New TableCell
                    Dim table1 As New Table
                    Dim tRow As New TableRow
                    Try
                    rowCnt = CInt(txtRowCnt. Text)
                    cellCnt = CInt(txtCellCnt .Text)
                    For rowCtr = 1 To rowCnt
                    For cellCtr = 1 To cellCnt
                    tCell.Text = "Row " & rowCtr & ", Cell " & cellCtr
                    ' Add new TableCell object to row
                    tRow.Cells.Add( tCell)
                    Next
                    ' Add new row to table
                    table1.Rows.Add (tRow)
                    Next
                    ''Dim aDataView As DataView = dset.Tables(0). DefaultView

                    Catch
                    lblPageLoad.Tex t = " " & Err.Description
                    End Try
                    End Sub

                    Comment

                    • katib
                      New Member
                      • Oct 2006
                      • 1

                      #11
                      Hello There

                      I need to do something similar, but I have textboxes as well . When the user fills in the textboxes and I click delete, all the textboxes become empty. How van I prevent this?

                      Comment

                      • tanmay79
                        New Member
                        • Oct 2006
                        • 2

                        #12
                        Hi roopesh

                        Caeck out this link and video, may be this is what you are looking for.

                        mms://wm.microsoft.co m/ms/uifx/asp_net_atlas.w mv

                        Regards
                        Tanmay.

                        Comment

                        Working...