user2463711
user2463711

Reputation:

ASP.NET dynamic ASP Table with TextBoxes - Save Values in ViewState

I've a .aspx Site with a ASP Table. In the code behind file I fill the table with rows, cells and in the cells are ASP TextBoxes.

At the first load I Fill the TextBoxes with Values out of a database. But after someone is editing the value and submit the Page with a created button, there are no Access to the programmaticaly created rows of the table.

now I have seen some postings that a dynamic created asp table is getting resetted by postback.

now I have a question, how can I get the values which are changed by users on the site?!

I tried to override the SaveViewState and LoadViewState, but SaveViewState is only called after the Page was loaded but not if someone is clicking a button?

I'd like to save the data of the Textboxes that i can use them in the code after the user clicked a button.

What can I do?

Upvotes: 2

Views: 5421

Answers (2)

matt-dot-net
matt-dot-net

Reputation: 4244

There are 3 keys here, expressed perfectly by @Alexander.

Here is a code example:

 <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>


    <form runat="server">
        <asp:PlaceHolder ID="placeHolder1" runat="server" />
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit"/>
    </form>

Code Behind:

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : Page
{
    private static readonly List<String> _listOfThings = new List<String> { "John", "Mary", "Joe" };
    private List<TextBox> _myDynamicTextBoxes;


    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        _myDynamicTextBoxes = new List<TextBox>();
        var i = 0;
        foreach (var item in _listOfThings)
        {
            var tbox = new TextBox {ID = "TextBox" + (i++),Text=item};
            placeHolder1.Controls.Add(tbox); //make sure you are adding to the appropriate container (which must live in a Form with runat="server")
            _myDynamicTextBoxes.Add(tbox);
        }
    }

    protected void Button1_Click(Object sender, EventArgs e)
    {
        foreach (var tbox in _myDynamicTextBoxes)
        {
            Response.Write(String.Format("You entered '{0}' in {1}<br/>", tbox.Text, tbox.ID));
        }
    }
}

Upvotes: 1

Alexander
Alexander

Reputation: 2477

a) Dynamically created controls must be created in the Page Init event. That way, they exists when the ViewState is restored (which happens before Page Load).

b) You must ALWAYS create them in Page Init, no matter whether its a PostBack or not.

c) Always create the controls in the same order.

Then, they automatically will keep their values during a PostBack.

Please read this: ASP.NET Page Life Cycle Overview

Upvotes: 1

Related Questions