0

我想保留用户控制值

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

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

代码:

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

添加VisaUserControl.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>
4

1 回答 1

0

The dynamic controls must be added on every postback, so that ViewState can maintain its values. For more details, please read the ASP.NET page life cycle.

于 2013-09-25T07:11:17.163 回答