I am trying to get an application to allow a user to select something for a number rows and then do something on the server side once the user submits the form. The problem I’m having is that if I reload the table, I just get the default values back and if I don’t, the table is empty. Here is the code:
<asp:Table ID="tbl" runat="server">
<asp:TableRow>
<asp:TableHeaderCell>Question</asp:TableHeaderCell>
<asp:TableHeaderCell>Answer</asp:TableHeaderCell>
</asp:TableRow>
</asp:Table>
c#:
protected System.Web.UI.WebControls.Table tbl1;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
init_tbl();
}
}
protected void init_tbl()
{
tbl1.BorderWidth = 1;
TableRow tr = new TableRow();
tc = new TableCell();
tc.Text = "text";
tc.BorderWidth = 1;
tr.Cells.Add(tc);
ddl = new DropDownList();
ddl.ID = "r" + index;
ddl.Attributes["runat"] = "server";
ListItem item;
for (int i = 1; i <= 10; i++)
{
item = new ListItem();
item.Text = i.ToString();
item.Value = i.ToString();
if (i.ToString().Equals(r.Trim()))
{
item.Selected = true;
}
ddl.Items.Add(item);
}
list.Add(ddl);
tc.Controls.Add(ddl);
tc.ID = "tblr" + index;
tr.Cells.Add(tc);
tbl1.Rows.Add(tr);
}
your problem is with the convoluted way asp.net deals with dynamic controls, you need to create the dynamic control on page init, before the view state is set so state of the controls is maintained on the post, see this article http://geekswithblogs.net/shahed/archive/2008/06/26/123391.aspx.
You should definatley look at the gridview or at the very least one of the repeater controls.