如何保留用户控件值

本文关键字:用户 控件 保留 何保留 | 更新日期: 2023-09-27 18:32:46

我想保留用户控件值

如果我再添加一行,以前的控件值不存在

我浏览了一些网站,但我无法清楚地理解

法典:

protected void Page_Load(object sender, EventArgs e)
    {    
        if (!IsPostBack)
        {
            ViewState["ControlCount"] = ViewState["ControlCount"] == null ? 2 : ViewState["ControlCount"];
        }
    }
   public int controlCount
    {
        get
        {
            int val = 0;
            try
            {
                val = (int)ViewState["ControlCount"];
            }
            catch (Exception e)
            {
                // handle exception, if required.
            }
            return val;
        }
        set { ViewState["ControlCount"] = value; }
    }

在这里我添加用户控件

   protected void addnewtext_Click(object sender, EventArgs e)
    {
        int i = controlCount++;
        for (int j = 0; j <= i; j++)
        {
            AddVisaControl ac = (AddVisaControl)Page.LoadControl("AddVisaControl.ascx");
            Label lb = new Label();
            string z = Convert.ToString(j + 1);
            lb.Text = "Visa " + z;
            rpt1.Controls.Add(lb);
            lb.Attributes.Add("class", "style8");
            rpt1.Controls.Add(ac);
            rpt1.Controls.Add(new LiteralControl("<BR>"))    
        }  
    }

AddVisaUserControl.ascx

 <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddVisaControl.ascx.cs" EnableViewState="false" Inherits="Pyramid.AddVisaControl" %>
<div id="divreg" runat="server">
<table id="tbl" runat="server">
    <tr>
    <td>
        <asp:Label ID="lbl2" runat="server"></asp:Label>
    </td>
</tr>
<tr>
<td> Visa Number:</td>
<td><asp:TextBox ID="txtUser" Width="160px" runat="server"/></td>
<td> Country Name:</td>
<td><asp:DropDownList ID="dropCountry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Type of Visa:</td>
<td><asp:DropDownList ID="dropVisa" Width="165px" runat="server"></asp:DropDownList></td>
<td> Type of Entry:</td>
<td><asp:DropDownList ID="dropEntry" Width="165px" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td> Expiry Date</td>
<td>
</td>
</tr>
</table>
</div>

如何保留用户控件值

必须在每次回发时添加动态控件,以便 ViewState 可以维护其值。有关更多详细信息,请阅读 ASP.NET 页面生命周期。