user776530
user776530

Reputation: 133

modifying a table asp.net

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);
    }

Upvotes: 0

Views: 922

Answers (3)

thevan
thevan

Reputation: 10364

You stored the Table in the ViewState and Use it as you want.

Upvotes: 0

rabs
rabs

Reputation: 1827

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.

Upvotes: 1

CraigW
CraigW

Reputation: 715

I would just make a list of questions and DataBind them to a repeater/gridview/datagrid (as @Cybernate said), then add an Event method to the OnItemDataBound of the databinder.

In the ItemDataBound event I would get a list of answers for each question DataItem and add them to a DropDownList like you were doing above.

When the user fills out all of the answers you just need to go through the Request.Form array and find all the answers that will be passed back.

Upvotes: 0

Related Questions