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

旧时模样 提交于 2019-12-12 17:07:14

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/16985472/asp-net-dynamic-asp-table-with-textboxes-save-values-in-viewstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!