views:

569

answers:

2

I am looking to create a dynamic survey. Where I generate all the question controls from the database. Below is an example of what I am trying to do (without the database part). I am able to display questions as seen below. I am unable to read the users input.

Does anyone have any ideas.

I have looked into the viewstate, but I can not seem to get it to work.

When the page is reloaded through a Post Back the controls are gone. I have looked at every event I can think of and there are no controls on the page. Until I create them again on the Page_Load event.

Where do I look to find the value of the user input on dynamicly created controls?

Page

<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>

Code File

     protected override void OnPreLoad(EventArgs e)
{
    base.OnPreLoad(e);
    foreach (Control item in form1.Controls)
    { }
}

protected void Page_PreInit(object sender, EventArgs e)
{
    foreach (Control item in form1.Controls)
    { }
}
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    foreach (Control item in form1.Controls)
    { }
}

protected override void OnSaveStateComplete(EventArgs e)
{
    base.OnSaveStateComplete(e);
    foreach (Control item in form1.Controls)
    { }
}
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    foreach (Control item in form1.Controls)
    { }
}
protected void Page_Load(object sender, EventArgs e)
{
    RadioButton rb;
    rb = new RadioButton();
    rb.ID = "rb_1";
    rb.Text = "yes";
    rb.GroupName = "question";
    form1.Controls.Add(rb);

    rb = new RadioButton();
    rb.ID = "rb_2";
    rb.Text = "no";
    rb.GroupName = "question";
    form1.Controls.Add(rb);

    rb = new RadioButton();
    rb.ID = "rb_3";
    rb.Text = "other";
    rb.GroupName = "question";
    form1.Controls.Add(rb);

    TextBox tb = new TextBox();
    form1.Controls.Add(tb);

    Button btn = new Button();
    btn.Text = "Save";
    form1.Controls.Add(btn);

    foreach (Control item in form1.Controls)
    {

    }
}
+1  A: 

You have to generate the controls with an unique id. You must be able to math each control-id with exactly one question in your database. After doing this, you are able to write back the answer to a specific question into a datbase.

Mork0075
+1  A: 

Edit: Create the controls in the OnInit function (during the Init event). Check this page.

Try to make 'rb' or 'tb' variables class-scoped. Or at least store the reference to the created controls in a list (or array) and then try to access them through it when you want.

Since you create the control in the OnInit function, they are created before loading of view state. So that when the view state gets loaded, values posted by the user are restored from the view state to the control and thus you can access it from your code. You just need to keep the reference to the controls.

gius