473,395 Members | 1,869 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

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.Count;
TableRow r = new TableRow();
TableCell c = new TableCell();

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

protected void Page_Load(object sender, EventArgs e)
{

}

Thanks and Regards
Roopesh
Jul 18 '06 #1
11 3620
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.Count;
TableRow r = new TableRow();
TableCell c = new TableCell();

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

Session["table2"] = table2;
}

protected void Page_Load(object 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
Jul 19 '06 #2
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.
Jul 19 '06 #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.
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
Jul 19 '06 #4
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
Jul 19 '06 #5
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(object sender, EventArgs e) {
populatePendingTasks();
populateCompletedTasks();
}

protected void populatePendingTasks() {
//connect_to_db_get_the_pending_tasks_against_partic ular_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.GetPendingTasks(userId);
Session["pendingTasks"] = 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.AutoPostBack = true;
chk.CheckedChanged += new
EventHandler(moveToCompleteHandler);
cell.Controls.Add(chk);
}
if (j == 1){
TextBox t = new TextBox();
t.ID = "text1" + i;
t.Text = tasks[i].Desc;
t.Width = 200;
cell.Controls.Add(t);
}
if (j == 2){
LinkButton lnk = new LinkButton();
lnk.ID = "edit1" + i;
lnk.Text = "Edit" + i;
cell.Controls.Add(lnk);

}
if(j == 3){
HiddenField h = new HiddenField();
h.ID = "hidden" + i;
h.Value = tasks[i].Id;
cell.Controls.Add(h);
}
row.Cells.Add(cell);
}
pending_table.Rows.Add(row);
}
//Session["pending_table"] = pending_table;
}

void moveToCompleteHandler(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.CheckBox)sender).ID;
int index = getIndex(id, pending_table,1);

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

HiddenField c =
(HiddenField)pending_table.Rows[index].Cells[1].FindControl("hidden" +
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.GetPendingTasks(uId);
Session["pendingTasks"] = ts;

List<Task> tasks = (List<Task>)Session["pendingTasks"];

//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.UpdateTask(task);

TableRow row_u = pending_table.Rows[index];

//removing the row and adding it to completed Table

pending_table.Rows.Remove(pending_table.Rows[index]);
completed_table.Rows.Add(row_u);

List<Task> tss = new List<Task>();
tss = comp.GetPendingTasks(uId);
Session["pendingTasks"] = tss;

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

}

protected void populateCompletedTasks()
{
//connect_to_db_get_the_completed_tasks_against_part icular_id
//get the session id from session object
string userId = "roopesh";
TaskComponent taskComp = new TaskComponent();
List<Task> tasks = new List<Task>();
tasks = taskComp.GetCompletedTasks(userId);
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.AutoPostBack = true;
chk.Checked=true;
chk.CheckedChanged += new
EventHandler(moveToPendingHandler);
cell.Controls.Add(chk);
}
if (j == 1)
{
TextBox t = new TextBox();
t.ID = "text2" + i;
t.Text = tasks[i].Desc;
t.Width = 200;
cell.Controls.Add(t);
}
if (j == 2)
{
LinkButton lnk = new LinkButton();
lnk.ID = "edit2" + i;
lnk.Text = "Edit" + i;
cell.Controls.Add(lnk);
lnk.Visible = false;
}
if (j == 3)
{
HiddenField h = new HiddenField();
h.ID = "hidden2" + i;
h.Value = tasks[i].Id;
cell.Controls.Add(h);
}
row.Cells.Add(cell);
} completed_table.Rows.Add(row);
}
Session["completed_table"] = completed_table;
}

void moveToPendingHandler(object sender, EventArgs e)
{
completed_table = (Table)Session["completed_table"];
string id = ((System.Web.UI.WebControls.CheckBox)sender).ID;

//int index = getIndex(id, completed_table, 2);
int index = getIndex(id, completed_table, 2);
HiddenField c =
(HiddenField)completed_table.Rows[index].Cells[1].FindControl("hidden2"
+ index);
string taskId = c.Value;

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

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

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

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

TableRow row_u = completed_table.Rows[index];
completed_table.Rows.Remove(completed_table.Rows[index]);
pending_table.Rows.Add(row_u);

Session["completed_table"] = completed_table;
Session["pending_table"] = pending_table;
List<Task> ts = new List<Task>();
ts = taskComp.GetPendingTasks(uId);
Session["pendingTasks"] = ts;

//string userId = "roopesh";
comp = new TaskComponent();
List<Task> tkss = new List<Task>();
tkss = comp.GetCompletedTasks(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.GetEnumerator();
while (myRowEnum.MoveNext())
{
IEnumerator myCellEnum = table.Rows[row_cnt].Cells.GetEnumerator();
while (myCellEnum.MoveNext())
{
current_cell = (TableCell)myCellEnum.Current;
CheckBox check = null;
if(mode == 1)
check =
(CheckBox)current_cell.FindControl("unchecked"+row _cnt);
if(mode == 2)
check =
(CheckBox)current_cell.FindControl("checked"+row_c nt);

current_row = (TableRow)myRowEnum.Current;
int indx = table.Rows.GetRowIndex(current_row);

if ((check.ID).Equals(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(taskId))
{
return tasks[i];
}} return null;
}}
Jul 20 '06 #6
Please tell if I need to cut short the code.

Regards
Roopesh
Jul 20 '06 #7
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(Sender as object, e as eventargs)

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

end if

createTable(ctype(viewstate("cou"),integer))
end sub

protected sub createTable(count as integer)
tableplcHld.controls.clear()
dim i,c as integer
itemtable = new table()
itemtable.width=unit.percentage(50)
itemtable.borderwidth=unit.pixel(2)

for i=0 to count-1

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

for c=0 to 2
itemcell(c) = new tablecell()
itemcell(c).HorizontalAlign = HorizontalAlign.left
itemcell(c).borderwidth=unit.pixel(1)
itemcell(c).width=unit.percentage(50)
if c<>2 then
itemcell(c).text = i & c
else
itemcell(c).controls.add(del_btn)
end if
next
itemrow = new tablerow
itemrow.cells.add(itemcell(0))
itemrow.cells.add(itemcell(1))
itemrow.cells.add(itemcell(2))
itemtable.rows.add(itemrow)
next
tableplcHld.controls.add(itemtable)
end sub

public sub buttonclick(sender as object , e as eventargs)
viewstate("cou") =ctype(viewstate("cou"),integer)+1
createTable(ctype(viewstate("cou"),integer))
end sub

public sub del_click(sender as object , e as eventargs)
viewstate("cou") =ctype(viewstate("cou"),integer)-1
createTable(ctype(viewstate("cou"),integer))
end sub

</script>
<html>
<head>
</head>
<body>
<form runat="server">
<table>
<tr>
<tD>
<asp:button id="createrows" runat=server onclick="buttonclick" width=80 text="Creat_Rows"/>
</tD>
</tR>
<Tr>
<td>
<asp:PlaceHolder 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.
Jul 21 '06 #8
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
Jul 21 '06 #9
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(ByVal sender As System.Object, ByVal e As System.EventArgs) 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.Text = " " & Err.Description
End Try
End Sub
Sep 22 '06 #10
katib
1
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?
Oct 14 '06 #11
Hi roopesh

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

mms://wm.microsoft.com/ms/uifx/asp_net_atlas.wmv

Regards
Tanmay.
Oct 15 '06 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Kirk Is | last post by:
Hi there. I'm trying to improve a simple javascript based graphics editor for Atari 2600 games (long story) with better use of CSS and Javascript. I'm a little weak on what CSS can and can't...
9
by: Michelle | last post by:
I have a div that is initially empty. Clicking on a button will add some text boxes and other controls so the user can add additional records. In IE all works fine but in Netscape 7.0 when I add...
6
by: fidodido | last post by:
I was asked to do this.... Dynamically move "text1" and "hidden1" into the "form1" ..... Not by creating new elements, but moving the "text1" and "hidden1" elements into the form using javascript,...
2
by: ezmiller | last post by:
Hi, I have some code (which I will paste in below) that writes out some HTML dynamically using the W3C DOM...the last part of the code write out a simple table. MY problem is that the table is...
18
by: blueapricot416 | last post by:
I am on a team designing the front end of an Intranet application. The backend guys will be using JSP and AJAX-like functionality to make server requests that must dynamically change elements on a...
11
by: GaryB | last post by:
Hi Guys, I've been battling with this one for hours - I hope that you can help me! My code modifies the <aon a page, from a standard document link into a link with a tailored onclick event. ...
6
by: tuxedo | last post by:
I have a fixed html structure, where only one form and a simple select menu will exist on an html page, as follows: <form action="order" method="POST"> <select name="dinner"> <option...
8
prino
by: prino | last post by:
Hi all, I've written code (in REXX) that takes files in legacy languages (PL/I, COBOL, z/OS assembler, etc) and converts them into HTML in a format similar to what's displayed in the z/OS ISPF...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.