Hi I am really stuck up in one of my development tasks since couple of days and I am unable to find out the exactly whats going on. Please help.
I am trying to add rows
You are able to see only one row added everytime because, dynamically created controls will not be available across postbacks.
When you click on add row first time, a post back happens, a third row is added. when you click in add row second time, the already added row would not be available and a new row gets added again. Finally you will be able to see only one row everytime.
Bottom line is you have to recreate the dynamically added controls everytime on postback in the page_load event, the reason being dynamically added server sontrols donot persist across postbacks
refer Why dynamically created user controls disappear when controls are not doing full postbacks? also
To maintain the viewstate of dynamically added controls you have to generate ids for the controls. When you recreate the controls during postback, recreate them with the same ids so that view state is maintained.
Use some standard logic to generate the ids for the controls. hope this helps.
Update:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
int num_row = (int)Session["No_of_Rows"];
for (int i = 2; i < num_row; i++)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TextBox tb = new TextBox();
CheckBox cb = new CheckBox();
row.ID = "rw" + i;
cell1.ID = "c" + i + "1";
cell2.ID = "c" + i + "2";
tb.ID = "txt" + i;
tb.EnableViewState = true;
cb.ID = "chk" + i;
cell1.Controls.Add(cb);
cell2.Controls.Add(tb);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
tbl.Rows.Add(row);
}
}
else
{
Session["No_of_Rows"] = 2;
}
}
protected void addRow(object sender, EventArgs e)
{
int num_row = (int)Session["No_of_Rows"]+1;
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
TextBox tb = new TextBox();
CheckBox cb = new CheckBox();
row.ID = "rw" + num_row;
cell1.ID = "c" + num_row + "1";
cell2.ID = "c" + num_row + "2";
tb.ID = "txt" + num_row;
tb.EnableViewState = true;
cb.ID = "chk" + num_row;
cell1.Controls.Add(cb);
cell2.Controls.Add(tb);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
tbl.Rows.Add(row);
Session["No_of_Rows"] = tbl.Rows.Count;
}
After entering the value in the tale column how to save all the values in the database table?